鍊錶 (刪除鍊錶中倒數第n個節點)的兩種演算法

2021-10-04 17:33:32 字數 1966 閱讀 6439

# -*- coding:utf-8 -*-

"""

author: leadingme

mail:[email protected]

mywebsite:leadingme.top

"""# 刪除鍊錶的倒數第n個節點

""" 演算法要求: 給定乙個鍊錶,刪除鍊錶的倒數第n個節點,並且返回鍊錶的頭結點(不帶頭結點)

示例:給定乙個鍊錶 1->2->3->4->5, n=2

當刪除倒數第二個節點後,鍊錶變為1->2->3->5

"""def

removenthfromend

(head, n)

:"""

:param head:

:param n:

:return:

"""pointer = head

length =

0while pointer:

# 求出鍊錶的長度(包含頭結點)

pointer = pointer.

next

length +=

1if length ==1:

# 鍊錶為空

return

none

pointer = head

if n >= length:

# 刪除的節點為第乙個節點, 刪除頭節點

head.

next

= head.

next

.next

else

:if n ==1:

# 刪除的節點為最後乙個節點, 刪除尾節點

for i in

range

(length-2)

: pointer = pointer.

next

pointer.

next

=none

else

:# 刪除的節點為中間某個節點

for i in

range

(length-n-1)

: pointer = pointer.

next

pointer.

next

= pointer.

next

.next

return head

def

removenthfromend2

(head, n)

:"""

:param head:

:param n:

:return:

"""if head is

none

:# 如果鍊錶為空,則返回none

return

none

left = right = head

si =

0while si < n:

si +=

1 right = right.

next

if right is

none

:# right為none,right移動到尾節點, 刪除第乙個節點

head= head.

next

return head

while right.

next

isnot

none

: left = left.

next

right = right.

next

if n ==1:

# 刪除最後乙個節點

left.

next

=none

else

: left.

next

= left.

next

.next

return head

鍊錶 刪除鍊錶的倒數第N個節點

給定乙個鍊錶,刪除鍊錶的倒數第 n 個節點,並且返回鍊錶的頭結點。示例 給定乙個鍊錶 1 2 3 4 5,和n 2.當刪除了倒數第二個節點後,鍊錶變為1 2 3 5.說明 給定的 n 保證是有效的。高階 你能嘗試使用一趟掃瞄實現嗎?definition for singly linked list....

鍊錶 刪除鍊錶的倒數第N個節點

給定乙個鍊錶,刪除鍊錶的倒數第 n 個節點,並且返回鍊錶的頭結點。示例 給定乙個鍊錶 1 2 3 4 5,和 n 2.當刪除了倒數第二個節點後,鍊錶變為 1 2 3 5.說明 給定的 n 保證是有效的。思路 精髓!弄個啞節點,可以直接避免節點數只有乙個的情況。先都指向啞節點,fast先走n 1步。然...

鍊錶 刪除鍊錶的倒數第N個節點

給定乙個鍊錶,刪除鍊錶的倒數第 n 個節點,並且返回鍊錶的頭結點。示例 給定乙個鍊錶 1 2 3 4 5,和n 2.當刪除了倒數第二個節點後,鍊錶變為1 2 3 5.說明 給定的 n 保證是有效的。高階 你能嘗試使用一趟掃瞄實現嗎?definition for singly linked list....