#!/usr/bin/env python
# coding: utf-8
"""實現鍊錶的逆序
給定乙個帶頭節點的單鏈表,將其逆序。
head->1->2->3->4->5
變為head->5->4->3->2->1
"""# 定義鍊錶的節點類
class
listnode
:def
__init__
(self, val=0,
next
=none):
self.val = val # 節點中儲存的資料
self.
next
=next
# 指向下乙個節點的指標
# 反轉鍊錶
defreverse_list_node
(head)
: temp = listnode(
)#臨時頭結點
while head !=
none
:next
= head.
next
# 備份 head的next
head.
next
= temp.
next
# 修改 head的next 指向temp後的節點
temp.
next
= head # 插入 將temp後插入head指向的節點
head =
next
# 移動 head,儲存next備份的節點
return temp.
next
# 返回temp後的第乙個節點
# 列印鍊錶
defprint_list_node
(head,title)
(f"----- -----"
)if head ==
none
("null"
)return
while head !=
none
(head.val,end="")
head = head.
next
print(""
)if __name__ ==
'__main__'
:# 構造節點
a = listnode(1)
b = listnode(2)
c = listnode(3)
d = listnode(4)
e = listnode(5)
# 連線節點
a.next
= b b.
next
= c c.
next
= d d.
next
= e print_list_node(a,
"原始鍊錶"
)# 反轉鍊錶
head = reverse_list_node(a)
print_list_node(head,
"逆序鍊錶"
)
用單向鍊錶(頭插法)實現棧
用單向鍊錶實現棧,入棧時,新建乙個node結點,並把鍊錶的最後乙個node結點指向這個新建的node 出棧時,將最後乙個結點的值用乙個臨時變數儲存並輸出,然後將結點置為null。package com.bhy.stacktest public class singlelinkedliststackd...
使用頭插法實現鍊錶逆序
用頭插法實現鍊錶逆序,本質上跟使用就地插解法 或者就地逆置法 的思想是一致的,只不過頭插法就是使用乙個新的頭結點代替新的煉表頭指標來實現鍊錶的逆序,這裡以五個節點的鍊錶為例,來實現該方法,具體的 如下 用頭插法實現列表逆序 include struct listnode void printlist...
資料結構鍊錶 頭插法 尾插法 雙向鍊錶
我們最近學了資料結構鍊錶中的尾插法,頭插法,雙向鍊錶 鍊錶的步驟 1.申請乙個新的節點空間 2.給新的節點賦值資訊域 3.修改這個節點的指標域,將節點連線起來 尾插法 顧名思義就是從節點的尾部進行插入,首先申請乙個節點空間,給新的節點賦值資訊域,然後修改這個 節點的指標域,寫鍊錶首先要判斷頭節點是否...