读书人

关于链表删除程序的修改,该如何解决

发布时间: 2012-03-15 11:50:38 作者: rapoo

关于链表删除程序的修改
下面是我写的一个链表的删除程序,虽然编译无错,但是在运行时在建立完链表后我还没输入所要删除的数就反馈说175846is not been found,然后又把新的链表打印出来。请问我错在哪里,该如何修改,望各位大大指教!
/* Note:Your choice is C IDE */
#include <stdio.h>
#include <malloc.h>

#define NULL 0
typedef struct Listnode
{
int data;
struct Listnode *next;
}List;

struct Listnode *creat(void){
struct Listnode *p1,*p2,*head;
head=p1=p2=(struct Listnode*)malloc(sizeof(struct Listnode));
printf( "please put in data: ");
scanf( "%d ",&p1-> data);
while(p1-> data!=NULL)
{
p1=(struct Listnode*)malloc(sizeof(struct Listnode));
printf( "please put in data: ");
scanf( "%d ",&p1-> data);
p2-> next=p1;
p2=p1;
}
p2-> next=NULL;
return(head);
}


struct Listnode *dele(struct Listnode *head,int num){
List *p1,*p2;

if(head==NULL)
{
printf( "the list is null!\n ");

}
p1=p2=head;
while(num!=p1-> data&&p1-> next!=NULL)
{
p1=p1-> next;
p2=p1;
}
while(p1-> data==num)
{
if(p1==head)
head=p1-> next;
else
p2-> next=p1-> next;
printf( "delete:%d\n ",num);
}
free(p1);

if(p1-> data!=num)
{
printf( "%ld not been found!\n ",num);
}

return(head);
}


struct Listnode show(struct Listnode *h){
List *p1;
p1=h;
do
{
printf( "data=%d ",p1-> data);
p1=p1-> next;
}
while(p1-> next!=NULL);
}



main(){
List *p;
int num;
p=(struct Listnode*)malloc(sizeof(struct Listnode));
p=creat();
printf( "\nplease input the dele data:\n ");
scanf( "dele data=%d ",&num);
p=dele(p,num);
show(p);

}


[解决办法]
#include <stdio.h>
#include <malloc.h>

#define NULL 0
typedef struct Listnode
{
int data;
struct Listnode *next;
}List;

struct Listnode *listcreat(void){
struct Listnode *p1,*p2,*head;
head=p1=p2=(struct Listnode*)malloc(sizeof(struct Listnode));
printf( "please put in data: ");
scanf( "%d ",&p1-> data);
while(p1-> data!=NULL)
{
p1=(struct Listnode*)malloc(sizeof(struct Listnode));
printf( "please put in data: ");
scanf( "%d ",&p1-> data);
p2-> next=p1;
p2=p1;
}
p2-> next=NULL;
return(head);
}


struct Listnode *dele(struct Listnode *head,int num){
List *p1,*p2;

if(head==NULL)
{


printf( "the list is null!\n ");

}
p1=p2=head;
while(num!=p1-> data&&p1-> next!=NULL)
{
p2=p1;
p1=p1-> next;
}
if(p1-> data==num)
{
if(p1==head)
head=p1-> next;
else
p2-> next=p1-> next;
printf( "delete:%d\n ",num);
free(p1);
}
else
{
printf( "%ld not been found!\n ",num);
}

return(head);
}


void show(struct Listnode *h){
List *p1;
p1=h;
do
{
printf( "data=%5d\n ",p1-> data);
p1=p1-> next;
}
while(p1-> next!=NULL);
}


void main(){
List *p;
int num;
p=(struct Listnode*)malloc(sizeof(struct Listnode));
p=listcreat();
printf( "\nplease input the dele data:\n ");
printf( "dele data= ");
scanf( "%d ",&num);
p=dele(p,num);
show(p);
}

读书人网 >C语言

热点推荐