首页 > 代码库 > 【LeetCode】 19. Remove Nth Node From End of List 解题小结

【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,

  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.

首先容易想到的是先遍历一次链表,计算链表长度L,然后再次遍历到L-n的位置删除结点。更好的办法是应用递归,从后往前n递减,到-1时就到了要被删除结点的前一个结点。

/** * 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) {        ListNode* node = new ListNode(0);        node->next = head;        removeNode(node, n);        return node->next;    }        void removeNode(ListNode* head, int& n){        if (!head) return;        removeNode(head->next, n);        n--;        if (n == -1)            head->next = head->next->next;        return;    }};

【LeetCode】 19. Remove Nth Node From End of List 解题小结