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

41.leetcode19_remove_nth_node_from_end_of_list

时间:2018-02-27 01:08:54      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:esc   obj   循环   ext   nod   0ms   slow   from   lis   

1.题目描述


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

删除链表中倒数第n个节点

For 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.

2.题目分析

Note:
Given n will always be valid.
Try to do this in one pass.

题目要求:①给的n都是有效的②最好一次遍历出结果

我自己是用的开辟新链表的方法。因为是要一次遍历,我一开始是直接让指针跨过要删除的节点,但总是不能删除链表最后一个节点。在网上看了大神的解决方案,感觉实在厉害。

3.解题思路

①开辟新链表(40ms)

 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         p=ListNode(0)
15         tail=p
16         p1=head
17         x=0
18         while p1!=None:
19             x+=1
20             p1=p1.next
21         x-=n #正向遍历的节点位置 
22         p1=head
23         y=0
24         while p1!=None:
25             if y!=x: #不是要删除的节点
26                 tail.next=ListNode(p1.val) #向链表中添加相同节点
27                 tail=tail.next
28             y+=1
29             p1=p1.next
30         return p.next #返回新链表

②双指针遍历(39ms)

 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 head==None: #考虑空链表
15             return head
16         fast=head #fast指针得到删除节点的位置
17         p=head #p指针控制循环
18         slow=None #删除节点的指针
19         i=0 
20         while p!=None:
21             if i!=n: #不等于n时,只p指针移动
22                 i+=1
23                 p=p.next
24                 continue
25             else: #等于n时,slow指针和fast指针开始移动
26                 r=fast
27 fast=fast.next 28 p=p.next 29 #当循环结束时,fast正是要删除的节点,slow是它的前一个节点 30 if slow==None: 31 return head.next 32 slow.next=fast.next #删除节点 33 return head

 4.解题感悟

看懂了大神的解决方案后,发现原来是删除节点的方式不大妥当。我的删除方法直接是head=head.next.next,所以要删除最后一个节点的话根本没办法解决。一快一慢的话就靠谱多了。

41.leetcode19_remove_nth_node_from_end_of_list

标签:esc   obj   循环   ext   nod   0ms   slow   from   lis   

原文地址:https://www.cnblogs.com/19991201xiao/p/8476678.html

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