Remove Nth Node From End of List

 

 

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def removeNthFromEnd(self, head, n):
 9         """
10         :type head: ListNode
11         :type n: int
12         :rtype: ListNode
13         """
14         if not head:
15             return None
16         dummy=ListNode(-1)
17         dummy.next=head
18 
19         for i in range(n):
20             if(head):
21                 head=head.next
22             else:
23                 return None
24         
25         if(head==None):
26             return dummy.next.next
27         
28         slow=dummy.next
29         while(head.next):
30             head=head.next
31             slow=slow.next
32         
33         slow.next=slow.next.next
34 
35         return dummy.next

 

posted @ 2020-03-20 22:34  7aughing  阅读(177)  评论(0编辑  收藏  举报