问题描述:
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.
方法一:直观想法,即将指针移动 L-n 下
1.将链表遍历一遍,计算出L,再计算L-n,得到该点
2.设定一个计数值size,当size<=n时候,指针不移动,大于n时,指针移动,则刚好移动到L-n
代码如下:
def removeNthFromEnd(self, head, n):
size = 1
cur = p = head
while cur.next:
size += 1
cur = cur.next
if size > n + 1:
p = p.next
if size == n:
return head.next
else:
p.next = p.next.next
return head
方法二:解答(为了降低遍历的次数,采取两个指针,时间复杂度降低为O(L) ):
- 设置两个指针p1,p2,两个指针的间隔为n
- 当p2指向链表的尾部的时候,p1指向n+1的位置
- 通过p1.next = p1.next.next的方式去掉第n个元素
- 特殊情况:当n=链表长度,返回空表
代码如下:
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
p1 = p2 = head
while n:
p2 = p2.next
n = n - 1
if p2 is None:
return head.next
while p2.next is not None:
p1 = p1.next
p2 = p2.next
p1.next = p1.next.next
return head
若把上述特殊情况一般化,则给链表增加一个头部first,代码如下
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
first = ListNode(0)
first.next = head
p1 = p2 = first
while n:
p2 = p2.next
n = n - 1
while p2.next is not None:
p1 = p1.next
p2 = p2.next
p1.next = p1.next.next
return first.next