#include<stdio.h>
#include<malloc.h>
typedef int datatype;
typedef struct link_node
{
datatype info;
struct link_node *next;
}node;
//创建链表????
node *createlist()
{
node *head,*p,*r;
head = r =(node *)malloc(sizeof(node));
datatype x,y;
scanf("%d",&x);
r->info = x;
scanf("%d",&y);
while(y!=0)
{
p=(node *)malloc(sizeof(node));
r->info = y;
r->next = p;
r=p;
scanf("%d",&y);
}
r->next = NULL;
return head;
}
//输出单链表各个节点的值
void printlist(node *head)
{
node *p=head;
if(!p)
{
printf("链表为空\n");
}
else
{
while(p)
{
printf("%d\n",p->info);
p=p->next;
}
}
}
//建立一个空的单链表
node *init_link_list()
{
return NULL;
}
//在单链表中查找值为x的节点
node *find_num_link_list(node *head, datatype x)
{
node *p=head;
while(p&&p->info!=x)
{
p=p->next;
return p;
}
}
//在单链表中查找第i个节点
node *find_pos_link_list(node *head ,int i)
{
int j;
node *p=head;
j=1;
while(p && i!=j)
{
p = p -> next;
j++;
}
return p;
}
//插入值为x的节点作为单链表的第一个节点
node *insert_in_front_link_list(node *head,datatype x)
{
node *p;
p=(node *)malloc(sizeof(node));
p->info=x;
p->next=head;
head=p;
return head;
}
//在单链表中第i个节点后插入一个值为x的新节点
node *insert_x_after_i(node *head, datatype x,int i)
{
node *p,*q;
q=find_pos_link_list(head,i);
if(!q)
{
printf("找不到第%d个节点,该节点不存在",i);
exit(1);
}
p=(node *)malloc(sizeof(node));
p->next = q->next;
q-> next=p;
return head;
}
//在链表中删除一个节点(包括头结点和其他节点)
node *delete_num_link_list(node *head,datatype x)
{
node *pre=NULL,*p;
if(!head)
{
printf("单链表为空");
}
p = head;
while(p && p->info !=x) //没有找到且没找完
{
pre=p;
p=p -> next;
}
if(!pre && p->info ==x)
{
head = head->next;
}
else
{
pre->next = p-> next;
free(p);
return head;
}
}
void main()
{
node *head;
head=createlist();
//insert_in_front_link_list(head,111);
printlist(head);
//insert_x_after_i(head,22,2);
delete_num_link_list(head,2);
printlist(head);
//find_pos_link_list(head,4);
}