LeetCode删除链表的倒数第n个结点

本文介绍了一种两遍遍历的方法来删除单链表中倒数第N个节点,首先通过一次遍历统计节点总数,再确定要删除节点的位置,最后完成删除操作并返回更新后的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1.首先遍历一遍链表,用count计数记录一共有多少个结点

2.第二遍便利链表,用count1找到删除结点的位置

3.删除结点

/**

 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
     if(head == NULL){
        return head;
    }
    struct ListNode *current_node = head;
    int count = 0;
    while(current_node != NULL){
        current_node = current_node->next;
        count++;
    }
    struct ListNode *current_node1 = head;
    int count1 = 0;
    if(n == count){
        struct ListNode *delete_node1 = head; 
        head = current_node1->next;
        free(delete_node1);
        return head;
    }
    while(current_node1->next != NULL && count1 < count - n - 1){
        current_node1 = current_node1->next;
        count1++;
    }
    if(count1 == count - n - 1&& current_node1->next != NULL){
        struct ListNode *delete_node = current_node1->next;
        current_node1->next = delete_node->next;
        free(delete_node);
        return head;
    }
    return head;




}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值