链表的基本操作

#include<stdio.h>
#include<malloc.h>
typedef struct List
{
    int data;
    List * next;
}list;


list * createlist()
{
    list * Head = (list*)malloc(sizeof(list));


    list  * cur= Head; //保存尾节点
    cur->next = NULL;
    int data;
    while(1)
    {  
        scanf_s("%d", &data);
        if (data < 0)
        {
            break;
        }
        else
        {
            list * pnew = (list*)malloc(sizeof(list));
            cur->next = pnew;
            pnew->next = NULL;
            pnew->data = data;
            cur = pnew;  //保存尾节点
        }

    }
    return Head;
}
void PrintfList(list *Head)
{
    if (Head == NULL)
    {
        return;
    }
    list * L = Head->next;
    while (L != NULL)
    {
        printf("%d\n", L->data);
        L = L->next;
    }

}
void InsertList(list*Head, int x, int y)
{
    if (Head == NULL)
    {
        return;
    }
    list *pre = Head;
    list *cur = Head->next;

    while (cur != NULL)
    {
        if (cur->data ==  x)
        {
            break;
        }
        pre = pre->next;
        cur = cur->next;
    }
    
    list * pnew = (list*)malloc(sizeof(list));
    pnew->data = y;
    pre->next = pnew;
    pnew->next = cur;
}
void DeleteList(list* Head,int x)
{
    if (Head == NULL)
    {
        return;
    }
    list *pre = Head;
    list *cur = Head->next;
    int flag = 0; //没有找到
    while (cur != NULL)
    {
        if (cur->data == x)
        {
            pre->next = cur->next;
            free(cur);
            flag = 1;
            break;
        }
        pre = pre->next;
        cur = cur->next;
    }
    if (flag == 0)
    {
        printf("not find the vlaue %d\n", x);
    }

}
void ClearList(list *Head)
{
    while (Head == NULL)
    {
        return;
    }
    list *del = Head;
    while (del != NULL)
    {
        Head = Head->next;  
        free(del);
        del = Head;
    }
}
void main()
{
    list *  Head = createlist();
    PrintfList(Head);
    InsertList(Head,5,4);
    PrintfList(Head);
    DeleteList(Head, 4);
    PrintfList(Head);
    ClearList(Head);
    PrintfList(Head);
}


面试题目:

写出一个函数,在链表的pHead头结点之后,插入一个新的结点。

 void insert(List *pHead, List * new)

{

        pHead->next = new;

         new->next = pHead->next;


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值