题目: 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:给定的 n 保证是有效的。
力扣链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
题解方法一:单指针的两次遍历
# 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:
# 单指针的两次遍历法
res = ListNode(0) #申请链表空间位置
res.next = head
dummy = head
length = 0
while dummy: #计算head长度
dummy = dummy.next
length +=1
if n>length: return None
dummy = res
for i in range(length-n): #定位到L-n节点
dummy = dummy.next
dummy.next = dummy.next.next #删除n字节,即L-n+1节点
return res.next
题解方法二:双指针的一次遍历
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 双指针的一次遍历
first = ListNode(0) #申请链表空间位置
first.next = head
second = first #双指针
for i in range(n+1): #first指针移动n+1步
first = first.next
res = second
while first: #双指针同时移动,直到first为NULL
first = first.next
second = second.next
second.next = second.next.next
return res.next
题解方法三:递归
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# 递归
global count
if head is None:
count =0
return None
head.next =self.removeNthFromEnd(head.next,n)
count +=1
return head.next if count==n else head