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.
需要注意当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
删除链表倒数第N个节点
本文介绍如何在单链表中删除倒数第N个节点,并提供了一个使用两个指针的方法来实现这一操作,确保在一次遍历中完成任务。
625

被折叠的 条评论
为什么被折叠?



