您的位置:首页 > 其它

链表基本操作(建立、修改,插入、删除、打印)

2013-08-17 16:19 691 查看
#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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐