c语言链表操作

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    int value;
    struct node *next;
} Node;
// 链表初始化
Node* initialList()
{
    Node *head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    return head;
}
// 创建新的节点
Node* creatNew(int val)
{
    Node *new = (Node *)malloc(sizeof(Node));
    new->value = val;
    new->next = NULL;
    return new;
}

// 按索引寻找节点
Node* find(Node *head, int index)
{
    Node *cur;
    int i = -1; // 头节点标为-1
    for (cur = head; cur != NULL; cur = cur->next, i++)
    {
        if (i == index)
        {
            return cur;
        }
    }
    printf("节点不存在\n");
    return NULL;
}

// 展示链表
void show(Node *head)
{
    Node *cur = head->next;
    while (cur != NULL)
    {
        printf("%d ", cur->value);
        cur = cur->next;
    }
}
// 添加
// 头插
void insertbyhead(Node *head, int val)
{
    Node *new = creatNew(val);
    new->next = head->next;
    head->next = new;
}
// 尾插
void insertbytail(Node *head, int val)
{
    Node *new = creatNew(val);
    Node *cur = head; // 从虚拟的头开始
    while (cur->next != NULL)
    {
        cur = cur->next;
    }
    cur->next = new;
}
// 按位置插入
void insertbyindex(Node *head, int val, int index)
{
    Node *pre = find(head, index - 1);
    Node *new = creatNew(val);
    new->next = pre->next;
    pre->next = new;
}

// 删除操作
// 按索引删除
void delete(Node *head, int index)
{
    Node *pre = find(head, index - 1);
    Node *cur = find(head, index);
    pre->next = cur->next;
    free(cur);
}

// 销毁链表(包括头节点也删除)
// 要对头节点进行操作所以要传入二级指针
void delete_all(Node **head)
{
    Node *point;
    while (*head != NULL)
    {
        point = (*head)->next;
        free(*head);
        *head = point;
    }
    *head = NULL;
}

void delete_excep(Node* head)
{
    Node* cur = head->next;
    Node* next_point;
    while (cur)
    {
        next_point = cur ->next;
        free(cur);
        cur = next_point;
    }
    head->next = NULL;
}
int main()
{
    Node* head = initialList();
    insertbyindex(head, 0, 0);
    insertbyindex(head, 1, 1);
    insertbytail(head, 2);
    //delete_all(&head); // 包括删除头
    delete_excep(head);
    show(head);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值