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

来源:互联网 发布:淘宝情趣店记事 编辑:程序博客网 时间:2024/06/05 00:08
#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;}