python實現從尾到頭打印單鏈表操作示例
更新時間:2020年02月22日 11:23:22 作者:franklin_yuan
這篇文章主要介紹了python實現從尾到頭打印單鏈表操作,結合實例形式分析了Python單鏈表的定義、判斷、添加、打印等相關操作技巧,需要的朋友可以參考下
本文實例講述了python實現從尾到頭打印單鏈表操作。分享給大家供大家參考,具體如下:
# coding=utf-8
class SingleNode:
def __init__(self, item):
self.item = item
self.next = None
class SingleLinkedList:
"""
is_empty() 鏈表是否為空
print_end_to_head() 從尾到頭打印單鏈表
append(item) 鏈表尾部添加元素
"""
def __init__(self):
self._head = None
def is_empty(self):
return self._head is None
def append(self, item):
if self.is_empty():
self._head = item
else:
cur = self._head
while cur.next:
cur = cur.next
cur.next = item
def print_end_to_head(self):
"""從尾到頭打印單鏈表"""
if self.is_empty():
print(None)
return
tmp = []
cur = self._head
while cur:
tmp.insert(0, cur)
cur = cur.next
for i in tmp:
print(i.item)
if __name__ == '__main__':
sl = SingleLinkedList()
sl.append(SingleNode(1))
sl.append(SingleNode(2))
sl.append(SingleNode(3))
sl.append(SingleNode(4))
sl.print_end_to_head()
運行結果:
4
3
2
1
PS:對象obj的打印,可使用如下語句實現:
print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python加密解密算法與技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。

