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.
给定单链表,删除倒数第n个节点。
基本思路:遍历一遍获取链表总长度,获取倒数第n个的正序位置seq,维护两个指针pre,node找到第seq位置,然后将
pre.next=node.next即可。这里要注意边界条件,seq==1,删除第一个节点,直接返回head.next即可。
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head==None:
return head
count = 0
node=head
while node!=None:
count += 1
node = node.next
seq = count - n + 1
if seq == 1:
return head.next
pre = None
node = head
while seq>1:
pre = node
node = node.next
seq -= 1
pre.next = node.next
node = None
return head
Could you do this in one pass?
利用双指针来定位倒数第n个节点位置,假设链表长度为l,第一个指针先移动n,然后第二个指针从头开始,第一个指针从n开始,这样当第一个到达尾部时,第二个即为倒数第n个,然后执行删除操作即可。
以12345 n=2 为例
第一个指针移动两步到达2位置
第二个指针从1出发,第一个指针从2出发,当第一个指针到达最后一个元素5时,此时第二个指针指向4,利用pre指针删除节点4即可
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head==None:
return head
pre = None
first = head
second = head
while n-1>=1:
n -= 1
first = first.next
while first.next!=None:
first = first.next
pre = second
second = second.next
if second==head:
return head.next
pre.next = second.next
return head
大神的代码,差不多:
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if n == 0:
return head
it = p = head
i = 0
while it:
it = it.next
i += 1
if i > n+1:
p = p.next
if n == i:
head = head.next
else:
p.next = p.next.next
return head