2018暑假第九題
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。(python)
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
說明:
給定的 n 保證是有效的。
進階:
你能嘗試使用一趟掃描實現嗎?
題目連結:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/
答案——
方法一:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
be = ListNode(None) #在連結串列最前面新增一個be空節點
be.next = head
p = be
p1 = p
p2 = p
p3 = p
length = 0
while p.next <> None: #獲得連結串列長度
length = length + 1
p = p.next
if n == length: #刪除第一個節點
head = head.next
elif n == 1: #刪除最後一個節點
for k in range(length -1):
p3 = p3.next
p3.next = None
else: #刪除中間的節點
for i in range(length - n):
p1 = p1.next
for j in range(length - n + 2):
p2 = p2.next
p1.next = p2
return head
方法二(進階):
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
be = ListNode(0)
be.next = head
p1 = be
p2 = be
for i in range(n + 1):
p1 = p1.next
while p1 <> None:
p1 = p1.next
p2 = p2.next
p2.next = p2.next.next
return be.next
使用兩個指標,保證兩指標的距離為n,當後面的指標到末尾時,前面的指標在倒數第n個位置上。