C语言创建带头结点的双向非循环链表并实现其元素插入操作的源程序

[复制链接]
查看11 | 回复1 | 2011-9-1 15:47:24 | 显示全部楼层 |阅读模式
#include
#include
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->next=head->prior=NULL;
for(j=4;j>=0;j--)
{
p1=(node *)malloc(sizeof(node));
p1->i=a[j];
p1->prior=head;
p1->next=head->next;
head->next=p1;
}
return head;
}
node * insert_list(node *head,int i,int num)
{
node *p,*q;
int j;
for(j=1,p=head->next;jnext;j++)
{
p=p->next;
}
q=(node *)malloc(sizeof(node));
q->i=num;
q->prior=p->prior;
q->next=p;
p->prior->next=q;
p->prior=q;
return head;
}
void printf_list(node *head)
{
node *p;
clrscr();
for(p=head->next;p;p=p->next)
{
printf("%d",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);
}
高手帮忙看下错在哪里了,为什么在第一个元素结点前插入时就可以正常输出,而在第一个元素之后的结点插入时输出的结果就是将插入元素之前的元素全部覆盖掉了?如输入3 79时,输出的结果为什么会是79 8 9呢?

回复

使用道具 举报

千问 | 2011-9-1 15:47:24 | 显示全部楼层
将移动结点那句"p=p->next"改成:q=p->next;q->prior=p;p=q;经调试成功,原因不明。...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行