題目
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
鏈接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
思路1
首先計算鏈表的長度,再判斷n是否表示的是第一個節點,若是,直接返回head.next,否則找到要刪除的節點的前兩個節點,最後刪除目標節點
代碼
# 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:
now=head
num=1
while(now.next):
now=now.next
num+=1
if(num==n):
return head.next
now=head
for i in range(num-n-1):
now=now.next
now.next=now.next.next
return head
思路2
雙指針,倒數第n個節點是指距離鏈表末尾的距離,所以定義一個快指針,先移動n個距離,在定義一個快指針,讓快慢指針一起移動,需要注意的是當快指針移動到倒數第二個時停止,方便刪除節點,此時慢指針所指的位置是目標節點的前一位,所以很簡單就能刪除節點。(記得判斷n是否爲第一個節點)
代碼
# 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:
slow=head
fast=head
while(n):
if fast.next:
fast=fast.next
n-=1
else:
return head.next
while(fast.next):
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return head