我写的一个链表,采用的是尾插法,其中进行删除操作。
为什么不能删除第一个节点的数据?其他的节点就可以。
代码如下:
#include "stdio.h"
#include "stdlib.h"
#define true 1
#define false 0
typedef struct node{
int data;
struct node *next;
}Node;
Node *head=NULL;
void winsert(int x) //插入节点,尾插法
{
Node *temp=(Node *)malloc(sizeof(Node));
Node *list=head;
temp->data=x;
temp->next=NULL;
if(head==NULL)
{
head=temp;
}
else
{ while(list->next!=NULL)
{
list=list->next;
}
list->next=temp;
}
}
void Print() //输出链表
{
Node *temp=head;
while(temp)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int dele(int x) //删除节点
{
Node *front=head;
Node *temp=head;
while(temp)
{ if(temp->data==x)
{ front->next=temp->next;
free(temp);
return true;
}
front=temp;
temp=temp->next;
}
return false;
}
int main()
{ int x;
printf("请输入要插入的数,直到负数结束:");
while(1)
{
scanf("%d",&x);
if(x<0)
break;
winsert(x);
}
printf("数据输入完成 ");
Print();
printf("请输入要删除的数:");
scanf("%d",&x);
if(dele(x))
{ printf("数据已删除:");
Print();}
else
printf("删除失败\n");
}