Remove Nth Node From End of List

Question

  1. Given a linked list, remove the nth node from the end of list and return its head.
  2. Note
  3. The minimum number of nodes in list is n.
  4. Example
  5. Given linked list: 1->2->3->4->5->null, and n = 2.
  6. After removing the second node from the end, the linked list becomes 1->2->3->5->null.
  7. Challenge
  8. O(n) time

题解

简单题,
使用快慢指针解决此题,需要注意最后删除的是否为头节点。让快指针先走n步,直至快指针走到终点,找到需要删除节点之前的一个节点,改变node->next域即可。

C++

  1. /**
  2. * Definition of ListNode
  3. * class ListNode {
  4. * public:
  5. * int val;
  6. * ListNode *next;
  7. * ListNode(int val) {
  8. * this->val = val;
  9. * this->next = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @param head: The first node of linked list.
  17. * @param n: An integer.
  18. * @return: The head of linked list.
  19. */
  20. ListNode *removeNthFromEnd(ListNode *head, int n) {
  21. if (NULL == head || n < 0) {
  22. return NULL;
  23. }
  24. ListNode *preN = head;
  25. ListNode *tail = head;
  26. // slow fast pointer
  27. int index = 0;
  28. while (index < n) {
  29. if (NULL == tail) {
  30. return NULL;
  31. }
  32. tail = tail->next;
  33. ++index;
  34. }
  35. if (NULL == tail) {
  36. return head->next;
  37. }
  38. while (tail->next) {
  39. tail = tail->next;
  40. preN = preN->next;
  41. }
  42. preN->next = preN->next->next;
  43. return head;
  44. }
  45. };

以上代码单独判断了是否需要删除头节点的情况,在遇到头节点不确定的情况下,引入dummy节点将会使代码更加优雅,改进的代码如下。

C++ dummy node

  1. /**
  2. * Definition of ListNode
  3. * class ListNode {
  4. * public:
  5. * int val;
  6. * ListNode *next;
  7. * ListNode(int val) {
  8. * this->val = val;
  9. * this->next = NULL;
  10. * }
  11. * }
  12. */
  13. class Solution {
  14. public:
  15. /**
  16. * @param head: The first node of linked list.
  17. * @param n: An integer.
  18. * @return: The head of linked list.
  19. */
  20. ListNode *removeNthFromEnd(ListNode *head, int n) {
  21. if (NULL == head || n < 1) {
  22. return head;
  23. }
  24. ListNode dummy(0);
  25. dummy.next = head;
  26. ListNode *preDel = dummy;
  27. for (int i = 0; i != n; ++i) {
  28. if (NULL == head) {
  29. return NULL;
  30. }
  31. head = head->next;
  32. }
  33. while (head) {
  34. head = head->next;
  35. preDel = preDel->next;
  36. }
  37. preDel->next = preDel->next->next;
  38. return dummy.next;
  39. }
  40. };

源码分析

引入dummy节点后画个图分析下就能确定headpreDel的转移关系了。