zoukankan      html  css  js  c++  java
  • 单链表的几个基本操作

    /*以头插法,创建长度为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("
    ");
    }
    
    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
    ");
        else
            printf("no
    ");
        return 0;
    }
    View Code
  • 相关阅读:
    JavaScript—— scroolleftoffsetleft 系列的含义以及浏览器兼容问题
    GCD
    Treap
    快速* 模板
    线性筛素数
    珂朵莉树
    One Night
    长整数相加运算(内含减法)。。= =
    骑士周游 非完美版。。= =
    《Windows取证分析》
  • 原文地址:https://www.cnblogs.com/alan-W/p/5887002.html
Copyright © 2011-2022 走看看