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

[LC] 19. Remove Nth Node From End of List

时间:2019-10-21 09:25:57      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:could   pre   list   pass   second   from   nod   class   mes   

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

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.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

 

 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         dummy = ListNode(-1)
15         dummy.next = head
16         cur, slow = dummy, dummy
17         while n > 0:
18             cur = cur.next
19             n -= 1
20         while cur.next is not None:
21             slow = slow.next
22             cur = cur.next
23         slow.next = slow.next.next
24         return dummy.next
25         

 

[LC] 19. Remove Nth Node From End of List

标签:could   pre   list   pass   second   from   nod   class   mes   

原文地址:https://www.cnblogs.com/xuanlu/p/11711312.html

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