您的位置:首页 > Web前端 > Node.js

leetcode 19 Remove Nth Node From End of List

2015-04-12 15:05 357 查看


Remove Nth Node From End of List

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

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.


Note:

Given n will always be valid.

Try to do this in one pass.
用两个指针p1=head, p2=head。先让p2后移n次,再同步后移至p2==Null即可。
需要注意当p2后移n次时,p2==Null的情况。

class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
p2=head;
while (n>0):
p2=p2.next
n-=1
<span style="color:#ff0000;">if p2==None:
return head.next</span>
p1=head
while p2.next:
p1=p1.next
p2=p2.next
p1.next=p1.next.next
return head
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: