数据结构,删除链表倒数第n个节点,并返回新的头节点

哈哈哈哈哈哈

//设总节点数x个

//需要让1号节点遍历到

//最后一个节点时,二号节点遍历到要删除节点前一个

//1,2号节点开始都指向新的头节点,

//由于代码中新加了个头节点

//1号需要走到x+1位置,需要移动x次

//first=first->next;

//2号需要走到正序的(1+x)-n个节点位置,就是删除节点前一个

//就需要走x-n次

//second=second->next;

//先让1号节点走1号节点要走的次数减去二号要走的次数

//x-(x-n) = n次;

//然后1号2号只需要走相同的次数就

//能到达相同目标了

// 删除倒数第 n 个节点

bash 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode {
    int val;
    struct ListNode *next;
} ListNode;

// 创建一个新的节点
ListNode* createNode(int val) {
    ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

//设总节点数x个
//需要让1号节点遍历到
//最后一个节点时,二号节点遍历到要删除节点前一个
//1,2号节点开始都指向新的头节点,

//由于代码中新加了个头节点
//1号需要走到x+1位置,需要移动x次 
//first=first->next;
//2号需要走到正序的(1+x)-n个节点位置,就是删除节点前一个
//就需要走x-n次
//second=second->next;

//先让1号节点走1号节点要走的次数减去二号要走的次数
//x-(x-n) = n次;
//然后1号2号只需要走相同的次数就
//能到达相同目标了

// 删除倒数第 n 个节点
ListNode* removeNthFromEnd(ListNode* head, int n) {
    if (head == NULL) {
        return NULL;
    }

    ListNode *dummy = (ListNode *)malloc(sizeof(ListNode));
    dummy->next = head;
    ListNode *first = dummy;
    ListNode *second = dummy;

    // 移动 first 指针 n 步,移动了n次
    for (int i = 0; i < n; i++) {
        first = first->next;
    }

    // 同时移动 first 和 second 指针,直到 first 到达链表末尾
    while (first->next != NULL) {
        first = first->next;
        second = second->next;
    }

    // 删除 second 的下一个节点
    ListNode *temp = second->next;
    second->next = temp->next;
    free(temp);

    ListNode *result = dummy->next;
    free(dummy);

    return result;
}

// 打印链表
void printList(ListNode *head) {
    while (head != NULL) {
        printf("%d -> ", head->val);
        head = head->next;
    }
    printf("NULL\n");
}

int main() {
    // 创建链表 1 -> 2 -> 3 -> 4 -> 5
    ListNode *head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);

    printf("Original list: ");
    printList(head);

    int n = 2;
    head = removeNthFromEnd(head, n);

    printf("After removing the %d-th node from end: ", n);
    printList(head);

    return 0;
}

运行结果

相关推荐
wuqingshun3141599 小时前
蓝桥杯 5. 交换瓶子
数据结构·c++·算法·职场和发展·蓝桥杯
我想进大厂10 小时前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂10 小时前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
lkbhua莱克瓦2410 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
转基因12 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
Forworder13 小时前
[数据结构]树和二叉树
java·数据结构·intellij-idea·idea
我想进大厂13 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
@Aurora.14 小时前
数据结构手撕--【二叉树】
数据结构·算法
悲伤小伞14 小时前
C++_数据结构_详解红黑树
数据结构
前端 贾公子14 小时前
力扣 83 . 删除排序链表中的重复元素:深入解析与实现
数据结构·算法