Skip to content

Latest commit

 

History

History
56 lines (37 loc) · 1 KB

19. Remove Nth Node From End of List.md

File metadata and controls

56 lines (37 loc) · 1 KB

19. Remove Nth Node From End of List

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

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.

Note:

Given n will always be valid.

Resolution:

像是数据结构课上的作业orz

Code:

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0);
        dummy.next = head
        
        last = dummy
        first = dummy
        if last.next is None:
            return head
        
        for k in range(n):
            last = last.next
        while last.next:
            last = last.next
            first = first.next
        # if first.next is not None:
        first.next = first.next.next
        # else:
        #     first.next = None
        return dummy.next