#include<stdio.h>
#include<stdlib.h>
struct chain
{
int value;
struct chain *next;
};
struct chain *create()
{
struct chain *head,*tail,*p;
int x;
head = tail = NULL;
while(scanf("%d",&x)==1)
{
p=(struct chain*)malloc(sizeof(struct chain));
p->value=x;
p->next=NULL;
if(head==NULL)
head = tail = p;
else
tail=tail->next=p;
}
return head;
}
struct chain *inlink(struct chain *head,int a,int b) //int a代表要插入的节点,int b代表创建节点的数据域
{
struct chain *p,*q,*s;
s = (struct chain *)malloc(sizeof(struct chain));
s->value=b;
if(head==NULL)
{
head = s;
head->next = NULL;
}
if(head->value == a)
{
s->next=head;
head = s;
}
else
{
p=head;
while((p->value!=a)&&(p->next!=NULL))
{
q=p;
p=p->next;
}
if(p->value == a)
{
q->next = s;
s->next = p;
}
else
{
p->next=s;
s->next=NULL;
}
}
return (head);
}
struct chain *dellink(struct chain *head,int a) //int a代表要删除的节点
{
struct chain *q,*p;
if(head == NULL)
printf("找不到节点!\n");
else if(head->value == a)
{
p = head;
head = head->next;
}
else
{
p=head;
while((p->value!=a)&&(p->next!=NULL))
{
q=p;
p=p->next;
}
if(p->value != a)
printf("链表不存在此节点!\n");
else
{
q->next = p->next;
free(p);
}
}
return (head);
}
void main()
{
struct chain *p,*q;
//q=create(); //链表的创建;
q=inlink(create(),3,0); //链表的插入;
//q=dellink(create(),2); //链表的删除;
while(q){ //输出链表;
printf("%d ",q->value);
p=q->next;
free(q);
q=p;
}
printf("\n");
}
单链表
最新推荐文章于 2024-10-06 12:03:03 发布