leetcode 19 Remove Nth Node From End of List

Jun 24, 2017


leetcode 19

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        head_list=[]
        tmp_head=head
        while tmp_head:
            head_list.append(tmp_head)
            tmp_head=tmp_head.next
        list_len=len(head_list)
        if n == list_len:
            if list_len > 1:
                return head_list[1]
            else:
                return None
        else:
            t1=head_list[-n-1]
            if t1.next:
                t1.next=t1.next.next
            return head