码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode19 Remove Nth Node From End of List

时间:2020-02-07 20:26:51      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:one   lin   turn   用两个   while循环   linked   第一个   二次   span   

 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

 

leetcode19 Remove Nth Node From End of List

标签:one   lin   turn   用两个   while循环   linked   第一个   二次   span   

原文地址:https://www.cnblogs.com/yawenw/p/12274263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!