反轉鍊錶
# 節點
class
node
(object):
def__init__
(self, elem)
: self.elem = elem
self.
next
=none
# 鍊錶
class
singlelist
(object):
def__init__
(self, head)
: self.head = head
# 反轉鍊錶
defreversesinglelist
(self, head)
:if head ==
none
or head.
next
==none
:return
l, m, r = head, head.
next
, head.
next
.next
while r:
m.next
= l l = m
m = r
r = r.
next
m.next
= l return m
if __name__ ==
'__main__'
: head = node(1)
head.
next
= node(2)
head.
next
.next
= node(3)
head.
next
.next
.next
= node(4)
print
("原鍊錶:"
)print
(head.elem)
print
(head.
next
.elem)
print
(head.
next
.next
.elem)
print
(head.
next
.next
.next
.elem)
singlelist = singlelist(head)
m = singlelist.reversesinglelist(singlelist.head)
print
("反轉後鍊錶:"
)print
(m.elem)
print
(m.next
.elem)
print
(m.next
.next
.elem)
print
(m.next
.next
.next
.elem)
判斷鍊錶是否有環(快慢指標,快指標每次走兩步,慢指標每次一步,如果有環,快指標會轉圈,快指標就會等於滿指標)
# 節點
class
node
(object):
def__init__
(self, elem)
: self.elem = elem
self.
next
=none
# 鍊錶
class
singlelist
(object):
def__init__
(self, head)
: self.head = head
# 判斷是否有環
defishasloop
(self, head)
: low, fast = head, head
while fast and fast.
next
: low = low.
next
fast = fast.
next
.next
if low == fast:
return
true
return
false
if __name__ ==
'__main__'
: head = node(1)
head.
next
= node(2)
head.
next
.next
= node(3)
head.
next
.next
.next
= head.
next
.next
singlelist = singlelist(head)
print
(singlelist.ishasloop(singlelist.head)
)
鍊錶筆試面試題
有些許錯誤,第乙個程式 1.已知鍊錶的頭結點head,寫乙個函式把這個鍊錶逆序 cpp view plain copy void list reverse head next null head p 遞迴方法 cpp view plain copy void list reverse2 list n...
面經 煉錶筆試題
鍊錶的基本題型主要就以下這幾種,其他的基本是在這基礎上引申出來,所以如果基本掌握這幾種單向鍊錶的題,鍊錶基本沒什麼太大問題了。1.刪除無頭非尾節點 2.鍊錶的氣泡排序 3.反轉鍊錶 4.在當前節點前插入乙個資料x 5.查詢鍊錶的中間節點。6.刪除單鏈表的倒數第k個節點 k 1 k 總長度 對於上面這...
常考煉錶筆試題(一)
1 刪除鍊錶中等於給定值 val 的所有節點。示例 輸入 1 2 6 3 4 5 6,val 6 輸出 1 2 3 4 5 思路 要刪除鍊錶中等於給定值的所有節點,我們可以定義乙個結果鍊錶,再結合尾插的方法來實現。定義乙個last引用,指向結果鍊錶的最後乙個節點,cur引用指向給定鍊錶的第乙個節點。...