19. 删除链表的倒数第 N 个结点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


// 方法一 两趟循环 或者用栈也可以,栈和两趟循环类似,不多说了
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    if (head == NULL) {
        return NULL;
    }
    struct ListNode *tail = head;
    int nodeCount = 0;
    while (tail != NULL) {
        nodeCount++;
        tail = tail -> next;
    }

    if (nodeCount == n) {
        tail = head;
        head = tail -> next;
        free(tail);
        tail = NULL;
        return head;
    }

    int i;
    tail = head;
    for (i = 0; i < nodeCount - n - 1; i++) {
        tail = tail -> next;
    }

    struct ListNode * tmp = tail;

    tmp = tail -> next;
    tail -> next = tmp -> next; 
    free (tmp);
    tmp = NULL;

    return head;
}





// 方法二 快慢双指针 一趟循环,双指针,第一个指针先走 n-1步,然后第二个指针开始走,然后两个指针同时走,等到第一个指针到尾结点,第二个指针刚好在倒数第n个节点,刚好删除掉即可
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    if (head == NULL) {
        return head;
    }
    struct ListNode * first = head;
    struct ListNode * second = head;
    int count = 0;
    while (first != NULL) {
        if (count < n + 1) {
            first = first -> next;
            count++;
            continue;
        }
        count++;
        first = first -> next;
        second = second -> next;
    }

    if (count == n) { // 头结点单独处理
        head = second -> next;
        free(second);
        second == NULL;
        return head;
    }

    first = second -> next;
    second -> next = first -> next;
    free(first);
    first = NULL;
    return head;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值