leetcode19 Remove Nth Node From End of List

 1 """
 2 Given a linked list, remove the n-th node from the end of list and return its head.
 3 Example:
 4 Given linked list: 1->2->3->4->5, and n = 2.
 5 After removing the second node from the end, the linked list becomes 1->2->3->5.
 6 """
 7 """
 8 看到这道题想法是用遍历两遍链表,第一次找出删除点,第二次删除
 9 其实可以注意 间距这个条件,用两个指针,一次遍历就能完成
10 """
11 """
12 Time Limit Exceeded
13 Last executed input
14 [1]
15 1
16 """
17 class ListNode:
18     def __init__(self, x):
19         self.val = x
20         self.next = None
21 
22 class Solution1:
23     def removeNthFromEnd(self, head, n):
24         total = 0
25         p = head
26         q = head
27         while p:
28             total += 1
29             p =  p.next
30         step = total - n -1
31         while step:
32             if q:
33                 q = q.next
34                 step -= 1
35         q.next = q.next.next
36         return head
37 
38 class ListNode:
39     def __init__(self, x):
40         self.val = x
41         self.next = None
42 
43 class Solution2:
44     def removeNthFromEnd(self, head, n):
45         pre = head
46         cur = head
47         # for _ in range(n):
48         #     cur = cur.next
49         # bug  注意for 和 while循环的使用
50         while n:            #利用间距 可以省去一次循环
51             cur = cur.next
52             n -= 1
53         if cur == None:  # 需要删除的节点为第一个节点时,即返回第二个节点为头节点的链表
54             return head.next
55         while cur.next:
56             cur = cur.next
57             pre = pre.next
58         pre.next = pre.next.next
59         return head

 

posted @ 2020-02-07 19:45  yawenw  阅读(110)  评论(0编辑  收藏  举报