卖萌的弱渣

I am stupid, I am hungry.

Remove Nth Node From End of List

Remove Nth Node from End of List

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

Example

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

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

Note

The minimum number of nodes in list is n.

Challenge

O(n) time

Solution

  • Time O(n)
  • Find the length of list and count which to delete
(Remove-Nth-Node-From-End-Of-List.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of linked list.
    @param n: An integer.
    @return: The head of linked list.
    """
    def removeNthFromEnd(self, head, n):
        # write your code here
        if head == None:
            return None
        length = 1
        tmp = head
        while tmp.next != None:
            length += 1
            tmp = tmp.next
        # corner case: n == length
        if n == length:
            return head.next
        # remove nth lement
        tmp = head
        num = length - n - 1
        while num > 0:
            num -= 1
            tmp = tmp.next

        if tmp.next != None:
            tmp.next = (tmp.next).next
        else:
            tmp.next = None

        return head