題目:
解法1:
- 先把鏈表轉(zhuǎn)換成list磷雇,刪除list的倒數(shù)第n個值雳窟,再把list轉(zhuǎ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:
l = []
while head:
l.append(head.val)
head = head.next
del l[len(l)-n]
if len(l)==0:
return
head = ListNode(l[0])
r = head
p = head
for i in l[1:]:
node = ListNode(i) # 新建一個節(jié)點
p.next = node # 節(jié)點連接到當(dāng)前鏈表的尾巴上
p = p.next # 鏈表指針向后移動
return r
解法2:
- 先遍歷一遍鏈表堕油,得到鏈表的長度count,進而得到要刪除節(jié)點正著數(shù)的位置肮之,即count-n掉缺。
- 再次遍歷一遍鏈表,當(dāng)遍歷到count-n-1時戈擒,刪除節(jié)點眶明,p.next = p.next.next實現(xiàn)刪除節(jié)點。
- 需要考慮特殊情況:如果要刪除的是頭結(jié)點筐高,那么count-n=0搜囱,所以在第二次遍歷的時候,count-n-1是取不到的凯傲,無法刪除犬辰,要單獨考慮。具體代碼如下:
# 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:
count = 0
p=head
while p:
p = p.next
count +=1
target = count-n
if count == n:
return head.next
p1 = head
while target>1:
p1 = p1.next
target-=1
p1.next = p1.next.next
return head
解法3:
- 使用快慢指針冰单,快指針先移動n步幌缝,慢指針再從頭開始移動,兩指針一起走诫欠,
直到快指針移動到鏈表末尾時結(jié)束涵卵。此時浴栽,慢指針對應(yīng)的就是要刪除節(jié)點的前一節(jié)點。
- 需要考慮一種特殊情況:刪除的是頭節(jié)點轿偎。具體代碼如下:
# 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, fast = head, head
while n:
fast= fast.next
n -= 1
if fast is None:
return head.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return head