#include <stdio.h>
#include <stdlib.h>
struct list
{
int data;
struct list *next;
};
//头插法建立链表
struct list *headcreate()
{
struct list *head, *p;
int N,i;
head=NULL;
printf("输入要建立的链表结点个数N=");
scanf("%d",&N);
printf("输入%d个数:",N);
for(i=0;i<N;i++)
{
p=(struct list *)malloc(sizeof(struct list));
scanf("%d",&p->data);
p->next=head;
head=p;
}
return head;
}
//尾插法建立链表
struct list *tailcreate()
{
struct list *head, *p, *q;
int N,i;
head=NULL;
printf("输入要建立的链表结点个数N=");
scanf("%d",&N);
printf("输入%d个数:",N);
for(i=0;i<N;i++)
{
p=(struct list *)malloc(sizeof(struct list));
scanf("%d",&p->data);
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
}
return head;
}
//打印链表
void print(struct list *head)
{
struct list *p;
p=head;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
//修改链表结点
void Modify(struct list *head, int X)
{
struct list *p;
p=head;
printf("将所有结点为5的修改为%d\n",X);
while(p)
{
if(p->data==5)
p->data=X;
p=p->next;
}
}
//插入节点
void Insert(struct list *head, int Z)
{
struct list *p,*r;
p=head;
printf("将所有结点为10的后面插入%d\n",Z);
while(p)
{
if(p->data==10)
{
r=(struct list *)malloc(sizeof(struct list));
r->data=Z;
r->next=p->next;
p->next=r;
}
p=p->next;
}
}
//删除结点
struct list *Delete(struct list *head, int Y)
{
struct list *p, *q;
p=head;
while(p)
{
if(p->data==Y)
{
if(p==head)
head=p->next;
else
q->next=p->next;
}
else
q=p;
p=p->next;
}
return head;
}
int main()
{
struct list *head;
head=headcreate();
printf("头插法建立链表:");
print(head);
head=tailcreate();
printf("尾插法建立链表:");
print(head);
Modify(head,10);
printf("修改结点后的链表:");
print(head);
Insert(head,20);
printf("插入结点后的链表:");
print(head);
head=Delete(head,10);
printf("删除结点后的链表:");
print(head);
return 0;
}
链表基本操作(建立、修改,插入、删除、打印)
最新推荐文章于 2023-04-07 11:02:16 发布