Leetcode19 - Remove Nth Node From End of List(链表)

题意

给定一个链表和数字n,要求删除从后往前数的第n个数。并且1 pass。

思路

用两个指针first和second,先让second往后跑n个,然后first和second一起往后挪动,直到second->next是NULL的时候,first->next就是我们要删除的节点。

感觉是个非常巧妙的思路,思想就是:我们要删除的节点和最后一个节点的距离差是n。

另外,一定要注意两个边界情况:
1. 链表为空
2. second往后跑n个过后,如果second为空,那么我们要删除的就是第一个节点。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head) return NULL;
        ListNode *first = head, *second = head;
        for (int i = 0; i < n; i++) second = second->next;
        if (!second) {
            //the Node to delete is the head;
            ListNode *tmp = head;
            head = head->next;
            delete(tmp);
            return head;
        } else {
            while (second->next) {
                first = first->next;
                second = second->next;
            }
            ListNode *tmp = first->next;
            first->next = first->next->next;
            delete(tmp);
        }
        return head;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值