LeetCode(19)--Remove Nth Node From End of List
2017-07-25 10:14
411 查看
采用两个指针,一个快指针一个慢指针。快指针先走,直到指向第n+1位置,然后快慢指针一起走,直到快指针走到链表尾部,这时候慢指针指向的就是倒数第n+1位置,这样访问其next即可删除该节点。
实现代码如下:
需要注意的特殊情况是要删除的结点是头结点时,此时访问不了前一位,需要特别考虑。
实现代码如下:
需要注意的特殊情况是要删除的结点是头结点时,此时访问不了前一位,需要特别考虑。
class Solution{ public: ListNode* removeNthFromEnd(ListNode* head, int n){ if (head == NULL || n < 0)return NULL; ListNode* fast = head; ListNode* slow = head; //m=n+1为寻找倒数第n个前一个数 int m = n + 1; //判断该链表长度与n的关系,fast指向第n+1,这样当fast遍历完链表时,slow将指向第倒数n+1个 while (fast&&m) { fast = fast->next; m--; } //链表长度小于n if (m > 1) { return NULL; } while (fast) { fast = fast->next; slow = slow->next; } //要删除的是头结点 if (m == 1) { head = head->next; delete slow; } else { ListNode* del = slow->next; slow->next = slow->next->next; delete del; } return head; } };
相关文章推荐
- 【LeetCode】19. Remove Nth Node From End of List (2 solutions)
- 个人记录-LeetCode 19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- Remove Nth Node From End of List_Leetcode_#19
- [LeetCode-19] Remove Nth Node From End of List(删除链表中倒数第N个节点)
- leetcode --19. Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- leetcode_19_Remove Nth Node From End of List (easy)
- leetcode 19. Remove Nth Node From End of List
- LeetCode笔记:19. Remove Nth Node From End of List
- leetcode-19. Remove Nth Node From End of List
- 【Leetcode】19. Remove Nth Node From End of List - 删掉链表倒数第n个节点
- LeetCode 19 Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List
- leetcode题解-328. Odd Even Linked List && 19. Remove Nth Node From End of List
- LeetCode---(19)Remove Nth Node From End of List
- [Leetcode 19, Easy] Remove Nth Node From End of List
- leetcode 19. Remove Nth Node From End of List
- [LeetCode - 双指针] 19. Remove Nth Node From End of List
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)