3.单链表:任意位置删除元素

 删除链表元素是通过两个指针操作符,一个指向连接位置,另一个指向删除位置

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

struct Node
{
    int data;
    struct Node *next;
};
struct Node *head;

void Insert(int data)
{
    struct Node *Temp = (struct Node *)malloc(sizeof(struct Node));
    if (Temp == NULL)
    {
        printf("Memory allocation failed\n");
        return; // 检查内存分配
    }
    Temp->data = data;
    Temp->next = NULL;

    if (head == NULL)
    {
        head = Temp; // 如果链表为空,直接将头指针指向新节点
    }
    else
    {
        struct Node *current = head; // 使用临时指针遍历链表
        while (current->next != NULL)
        {
            current = current->next;
        }
        current->next = Temp; // 将新节点插入到链表末尾
    }
}

void Delete(int n)
{
    struct Node *Temp = head;
    if (Temp == NULL)
    {
        printf("Memory allocation failed\n");
        return; // 检查内存分配
    }

    if (n == 1)
    {
        head = Temp->next;
        free(Temp);
        return;
    }

    int i;
    for (i = 0; i < n - 2; i++) // 大于2,才往后移动
        Temp = Temp->next;

    struct Node *Temp2 = Temp->next;
    Temp->next = Temp2->next;
    free(Temp2);
}

void Print()
{
    struct Node *temp = head;
    printf("List is ");
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

int main()
{
    head = NULL;
    // 插入
    Insert(1);
    Insert(2);
    Insert(3);
    Insert(4);
    Insert(5);

    // 删除
    Delete(5);

    Print();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值