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

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值