#include<stdio.h>
typedef struct node
{
int i;struct node *next,*prior;
}s;
s* create_list()
{
int a[]={1,2,3,4,5},j=4;
s *h,*p;
h=(s *)malloc(sizeof(s));
h->next=h->prior='\0';
while(j>=0)
{
p=(s *)malloc(sizeof(s));
p->i=a[j];j--;p->next=h->next;h->next=p;
}
return h;
}
insert_list(s *head,int i,int c)
{
s *p=head->next,*q;int j=0;
while(j<i) {p=p->next;j++;}
if(j==i) {q=(s *)malloc(sizeof(s));q->i=c;p->prior->next=q;q->prior=p->prior;
p->prior=q;q->next=p;}
}
printf_list(s *head)
{
s *p=head->next;
while(p!='\0')
{printf("%d",p->i);p=p->next;}
}
main()
{
struct node *head;int i,c;
clrscr();
head=create_list();
printf_list(head);
scanf("%d",&c);
insert_list(head,i,c);
printf_list(head);
}
高手帮忙看下错在哪里了?谢谢!
/*
创建函数和插入函数已全部重写,并在必要的地方增加了注释。 截图是在VC++ 6.0环境下的运行结果。
*/
#include<stdio.h>
#include <stdlib.h>
typedef struct node {
int i;
struct node *next,*prior;
}s;
s *create_list() {
int a[] = {2,4,6,8,10},n = sizeof(a)/sizeof(a[0]);
s *p,*q,*head;
head = q = p = (s *)malloc(sizeof(s));
head->i = 0; // 0作为链表头结点数据
p->next = q->prior = NULL;
while(--n >= 0) {
q = (s *)malloc(sizeof(s));
q->i = a[n];
p->next = q;
q->prior = p;
p = q; // p下移到新结点
}
p->next = NULL;
return head;
}
void insert_list(s *head,int c) {
s *q,*p = head;
q = (s *)malloc(sizeof(s));
q->i = c;
while((p->next != NULL) && (p->next->i > c)) p = p->next;
if(p->next->i < c) { // 插在表中间
q->next = p->next;
p->next->prior = q;
q->prior = p;
p->next = q;
}
else if(p->next == NULL) { // 插在尾部
p->next = q;
q->prior = p;
q->next = NULL;
}
// 如果表中已有元素同样大小的i = c,则无息返回。
}
void printf_list(s *head) {
s *p = head;
int n = 0;
while(p->next != NULL) {
printf("%3d : %3d\n",n + 1,p->next->i);
p = p->next;
n++;
}
printf("\n");
}
main() {
struct node *head;
int c;
// clrscr();
head = create_list();
printf_list(head);
printf("请输入插入的数据 : ");
scanf("%d",&c);
insert_list(head,c);
printf_list(head);
return 0;
}