题目描述:
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
解题思路:
解法一:
本题的关键是找到倒数第N个结点,然后将第N-1个节点与第N个结点链接起来。数组可以直接读取总长从后向前遍历删除即可但是链表不行,所以我们需要先做一遍遍历,确定链表总长,在通过总长-N得到需要删除节点的正向位置,在进行删除操作。要注意的是python是从0开始计数的所以正向位置为j=i-n-1.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dhead = ListNode(next = head)
fas = dhead
low = dhead
i = 0
while fas:
fas = fas.next
i+=1
j = i-n-1
k= 0
while k <j:
low = low.next
k+=1
low.next = low.next.next
return dhead.next
解法二:双指针
为了更快的找到倒数第N个数,我们使用两个指针,快指针先移动N步,然后慢指针和快指针一起移动,在移动到链表末尾时快指针自然比慢指针快N步,慢指针位置也就是倒数第N个结点所在位置然后将第N-1个结点与第N+1个结点链接起来。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dhead = ListNode(next = head)
fas = dhead
low = dhead
i = 0
while i<=n:
fas = fas.next
i+=1
while fas != None:
fas = fas.next
low = low.next
low.next = low.next.next
return dhead.next