Leetcode 19 Remove Nth Node From End of List 超简洁代码

原创 2016年08月29日 21:00:07

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

用一次遍历删除单链表从末尾数的第n个节点。

利用类似DFS的递归解决,自认为还是挺简洁的。

既然是Leetcode上的基础题,就要小题大做,我去看了一下discuss,

发现有人用一种快慢指针的方法,即快指针先走n步,然后两者同时走,当快指针走到尾部时,慢指针就是要删除的节点,想法也挺好的。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int cnt=0;
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if(head==NULL) return NULL;
        head->next=removeNthFromEnd(head->next,n);
        if(++cnt==n)
            return head->next;
        return head;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

[leetcode: Python]19. Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.For example,Given ...
  • NXHYD
  • NXHYD
  • 2017-05-19 08:28
  • 99

LeetCode#19. Remove Nth Node From End of List

题目:删除链表倒数第n个元素

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

LeetCode-19 Remove Nth Node From End of List(移除尾部第N个节点)

LeetCode-19 Remove Nth Node From End of List Given a linked list, remove the nth node from the end o...

LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)

题目:http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ Given a linked list, remove t...

LeetCode 19. Remove Nth Node From End of List

19. Remove Nth Node From End of ListGiven a linked list, remove the nth node from the end of list an...

LeetCode笔记:19. Remove Nth Node From End of List

删除链表倒数第n个节点

Leetcode 19. Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head. For example, ...

[C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)

Problem: Given a linked list, remove the nth node from the end of list and return its head. For exam...

Leetcode_19_Remove Nth Node From End of List

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41778305 Given a linked list, ...

【Leetcode】19. Remove Nth Node From End of List

方法一: 思路: (1)若链表为空,直接返回null。 (2)求链表的长度len。 (3)若n==len,则删除的是第一个节点,直接删除后返回即可。 (4)从头开始遍历链表,找到待删除节点cur,并用...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)