单链表的几个基本操作

/*以头插法,创建长度为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

 

posted @ 2016-09-19 22:34  声声醉如兰  阅读(378)  评论(0编辑  收藏  举报