輸入乙個鍊錶,按煉錶值從尾到頭的順序返回乙個arraylist。
思路:
1、第一種方法是正常從頭到尾列印鍊錶,儲存在列表或者棧中,如果儲存在列表中就翻轉一下列表,儲存在棧中就直接pop元素即可(利用棧後進先出特性)
2、將鍊錶翻轉,然後輸出鍊錶元素
solution:
python
(1)# -*- coding:utf-8 -*-
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class solution:
# 返回從尾部到頭部的列表值序列,例如[1,2,3]
def printlistfromtailtohead(self, listnode):
# write code here
arraylist =
while listnode:
listnode = listnode.next
return arraylist[::-1]
(2)# -*- coding:utf-8 -*-
# class listnode:
# def __init__(self, x):
# self.val = x
# self.next = none
class solution:
# 返回從尾部到頭部的列表值序列,例如[1,2,3]
def printlistfromtailtohead(self, listnode):
# write code here
if listnode == none:
return
cur = listnode
pred = cur.next
cur.next = none
while pred:
tmp = pred.next
pred.next = cur
cur = pred
pred = tmp
arraylist =
while cur:
cur = cur.next
return arraylist
劍指offer(3) 從尾到頭列印鍊錶
輸入乙個鍊錶,從尾到頭列印鍊錶每個節點的值。輸入為鍊錶的表頭 輸出為需要列印的 新鍊錶 的表頭 鍊錶是一種動態資料結構,是因為在建立鍊錶時,無須知道鍊錶的長度。當插入乙個結點時,我們只需要為新結點分配記憶體,然後調整指標的指向來確保新結點被鏈結到鍊錶中。記憶體分配不是在建立鍊錶時一次性完成,而是每新...
劍指offer 3 從尾到頭列印鍊錶
coding utf 8 class listnode def init self,x self.val x self.next none class solution 返回從尾部到頭部的列表值序列,例如 1,2,3 def init self self.result def printlistfr...
劍指offer 3 從尾到頭列印鍊錶
程式設計資料獲取 codelab 輸入乙個鍊錶,按煉錶值從尾到頭的順序返回乙個arraylist,鍊錶定義如下 struct listnode 下面提供3種思路 1 正序遍歷並儲存,逆序輸出 class solution reverse vecval.begin vecval.end 這裡得益於re...