#include<stdio.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node* next;
} NODE,*PNODE;//将类型 struct Node 重命名为 Node_t
PNODE create_node(int x)
{
printf("---create_node---\r\n");
PNODE newnode = (PNODE)malloc(sizeof(NODE));
if (NULL == newnode) //内存分配失败
{
printf("fail to distribute memory,the procedure is over!\n");
return (PNODE)1;
}
newnode->data = x;
newnode->next = NULL;
return newnode;
}
PNODE create_list_scanf(void)
{
printf("---create_list_scanf---\r\n");
PNODE head=NULL, tail=NULL, p;//指针必须初始化,否则出错(野指针)
int x;
while(scanf("%d", &x) == 1)//当输入不为整数时结束
{
p=create_node(x);
if(head == NULL)
{
head=tail= p;
}
else
{
tail->next = p; //先连起来,再把指针放去尾部
tail = p;
}
}
return head;
}
void list_print(PNODE head)
{
PNODE p = head; //定义一个静态指针变量p指向头节点
//遍历所有结点
printf("---list_print---\r\n");
while( (p->next)!=NULL )
{
printf("%d->", p->data);//打印数据
p=p->next;
}
printf("NULL\r\n");
}
PNODE list_insert(PNODE head,int i,int x)
{
PNODE p=head;//p是前驱结点
int a=0;
printf("list_insert\r\n");
for(a=1;a<i;a++)
{
p=p->next;//查找出第i个位置的前驱结点
}
PNODE pNew=create_node(x);
pNew->next=p->next;
p->next= pNew;
return head;
}
PNODE list_delect(PNODE head,int x)
{
printf("---list_delect---\r\n");
// 注意:踩坑点。创建指针之后,没有初始化指针,导致程序出错死掉。错误做法例如:PNODE p,del;
PNODE p = head; //p是前驱
PNODE del = p->next; //del是找到要删除的结点
if (del == NULL)
{
printf("The linked list is empty!\r\n");
return;
}
while(del)
{ //查找数据x的位置
if( x == del->data )
{
// printf("del->%d\r\n",del->data);
p->next=del->next;
free(del);
break; //掉坑点:没有加break跳出while循环
}
else
{
del=del->next;//指向下一个结点
}
}
return head;
}
int main()
{
PNODE head=NULL;
head=create_list_scanf();
list_print(head);
list_delect(head,3);
list_print(head);
}
运行结果: