class Solution {
public:
    int N = 0;
    int LEN = 0;

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int i = 0;
        ListNode* node = head;
        N++;
        LEN = max(LEN, N);
        if (node->next != NULL)
        {            
            ListNode* Next = removeNthFromEnd(node->next, n);
            N--;
            if (n == LEN - N)
            {
                node->next = Next->next;
            }
        }
        if (n == LEN)
        {
            return head->next;
        }
        return node;
    }
};

 补充一个python的实现:

 1 class Solution:
 2     N = 0
 3     LEN = 0
 4     def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode':
 5         self.N += 1
 6         self.LEN = max(self.N,self.LEN)
 7         
 8         CN = self.N - 1
 9         node = head
10         if node.next != None:
11             nextnode = self.removeNthFromEnd(node.next,n)
12         index = self.LEN - n - 1
13         if CN == index:
14             node.next = nextnode.next
15         if n == self.LEN:
16             return head.next
17         return node

 

另一种快慢指针的实现不需要递归:

 1 public ListNode removeNthFromEnd(ListNode head, int n) {
 2     ListNode dummy = new ListNode(0);
 3     dummy.next = head;
 4     ListNode first = dummy;
 5     ListNode second = dummy;
 6     // Advances first pointer so that the gap between first and second is n nodes apart
 7     for (int i = 1; i <= n + 1; i++) {
 8         first = first.next;
 9     }
10     // Move first to the end, maintaining the gap
11     while (first != null) {
12         first = first.next;
13         second = second.next;
14     }
15     second.next = second.next.next;
16     return dummy.next;
17 }

 

python版本:

 1 class Solution:
 2     def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
 3         dm = ListNode(0)
 4         dm.next = head
 5         slow,fast = dm,dm
 6         for i in range(n):
 7             fast = fast.next
 8         while fast != None and fast.next != None:
 9             slow = slow.next
10             fast = fast.next
11         if slow.next != None:
12             slow.next = slow.next.next
13             return dm.next
14         return None

 

posted on 2018-10-06 10:39  Sempron2800+  阅读(222)  评论(0编辑  收藏  举报