单链表的几个基本操作

/*以头插法,创建长度为n的单链表,并实现对其的增、删、改、查*/

 

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};

struct node *Creat_List(struct node *head, int n)    //创建链表
{
    struct node *p;
    for(int i=0;i<n;i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d",&p->data);
        p->next = head;
        head = p;
    }
    return head;
}

void Put(struct node *head)      //打印链表
{
    struct node *p;
    p = head;
    while(p != NULL)
    {
        printf("%d ",p->data);
        p = p->next;
    }
    printf("\n");
}

struct node* Insert(struct node *head,int k,int num)          //在k处增加元素num
{
    struct node *p;
    p = head;
    for(int i=0;i<k;i++)
    {
        p = p->next;
    }
    struct node *temp;
    temp = (struct node *)malloc(sizeof(struct node));
    temp->data = num;
    temp->next = p->next;
    p->next = temp;
    return head;
}

struct node *Delete(struct node *head, int k)
{
    struct node *p;
    p = head;
    for(int i=1;i<k-1;i++)
    {
        p = p->next;
    }
    struct node *temp;
    temp = p->next;
    p->next = temp->next;
    return head;
}

bool Find(struct node *head,int num)
{
    struct node *p;
    p = head;
    while(p != NULL)
    {
        if(p->data == num)
        {
            return true;
        }
        p = p->next;
    }
    return false;
}

struct node *Change(struct node *head,int k,int num) //将数字k改为num
{
    struct node *p;
    p = head;
    while(p!=NULL)
    {
        if(p->data == k)
        {
            p->data = num;
        }
        p = p->next;
    }
    return head;
}

int main()
{
    int n;                  //链表长度
    scanf("%d",&n);
    struct node *head=NULL;
    head = Creat_List(head, n);
    Put(head);
    head = Insert(head,2,1000);
    //Put(head);
    head = Delete(head,4);
    //Put(head);
    head = Change(head,4,6);
    //Put(head);
    bool ok = Find(head,7);
    if(ok)
        printf("yes\n");
    else
        printf("no\n");
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/alan-W/p/5887002.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值