C语言实现的双向链表插入程序

#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;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-08-30
//双向链表
#include<stdio.h>
#include <malloc.h>
typedef struct node
{
int i;
struct node *next,*prior;
}node;

node* create_list()
{
int a[]={1,2,3,8,9};
int j;
node *head,*p1,*p2;
p2=head=(node *)malloc(sizeof(node));
head->i=a[0];
head->next=head->prior=NULL;
for(j=1;j<5;j++)
{
p1=(node *)malloc(sizeof(node));
p1->i=a[j];
p1->prior=p2;
p1->next=NULL;

p2->next=p1;
p2=p1;
}
return head;
}

node * insert_list(node *head,int i,int num)
{
node *p,*q;
int j;

for(j=0,p=head;j<i&&p->next;j++)
{
p=p->next;
}

q=(node *)malloc(sizeof(node));
q->i=num;

q->prior=p->prior;
q->next=p;
if(i==0)//插入结点作为表头
{
head=q;
}
else
{
p->prior->next=q;
}
p->prior=q;

return head;
}

void printf_list(node *head)
{
node *p;
for(p=head;p;p=p->next)
{
printf("%d\t",p->i);
}
printf("\n");
}

void main()
{
struct node *head;

int i,num;
head=create_list();
printf_list(head);

scanf("%d",&i);
scanf("%d",&num);
head=insert_list(head,i,num);
printf_list(head);
}本回答被提问者采纳
第2个回答  2011-08-30
初始化