读书人

扭结老久的关于线性链表输出、插入、删

发布时间: 2013-06-25 23:45:41 作者: rapoo

纠结老久的关于线性链表输出、插入、删除的程序,求大神帮忙!
#include<stdio.h>
#include<stdlib.h>

struct node *head;
struct node
{
int d;
struct node *next;
};
void outputlink()
{
struct node *p=head;
if(head==NULL)
{
printf("链表为空!\n");
return;
}

while(head!=NULL)
{
printf("%d ",p->d);
p=p->next;
}
}
void insert(int x,int y)
{
struct node *p,*q;
q=head;
p=(struct node *)malloc(sizeof(struct node));
p->d=y;
if(head==NULL)
{
head=p;return;
}
while((q->d)!=x&&(q->next)!=NULL)
{
q=q->next;
}
if((q->next)==NULL)
{
q->next=p;return;
}
if((q->d)==x)
{
p->next=q;
q=p;
}
}
void deletelink(int x)
{
struct node *p=head;
if(head==NULL)
{
printf("链表为空,无删除元素!\n");
return;
}
if((head->d)==x)
{
head=head->next;return;
}
while((p->d)!=x&&(p->next)!=NULL)
{
p=p->next;
}
if((p->d)==x)
{
p=p->next;
return;
}
if((p->next)==NULL)
{
printf("链表中无要删除元素!\n");
}
}
void main()
{
void outputlink();
void insert(int x,int y);
void deletelink(int x);
head=NULL;
printf("第一次扫描链表中的元素:\n");
outputlink();
insert(10,10);
insert(10,20);
insert(10,30);
insert(40,40);
printf("第二次扫描链表中的元素:\n");
deletelink(30);
deletelink(50);
printf("第三次扫描链表中的元素:\n");
}
链表
[解决办法]
void outputlink() 中 while(head!=NULL)
改为while(p != NULL) // 否则死循环

插入时没有处理好连接关系,正确逻辑应该是找到值为x的节点p和上一个节点pPre(假设你是前插),让pPre->next = pNew,pNew->next = p;

删除时
while((p->d)!=x&&(p->next)!=NULL)
改为while(p && (p->d != x))
正确的逻辑是 找到值为x的节点p后,需要保存前一个节点指针pPre,然后指向删除节点的next(pPre->next = p->next),然后删除要删除的节点p
[解决办法]
删除的时候在处理完连接后,要用free(p);来真正释放节点占用的内存,否则会有内存泄露
[解决办法]
有什么好纠结的 debug一下不就ok了

读书人网 >C语言

热点推荐