本文主要是介绍【剑指offer】JZ6 从头到尾打印链表(Python),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
python题解
class ListNode(object):def __init__(self):self.val = Noneself.next = None#尾插法
def creatlist_tail(lst):L = ListNode() #头节点first_node = Lfor item in lst:p = ListNode()p.val = itemL.next = pL = preturn first_node
#头插法
def creatlist_head(lst):L = ListNode() #头节点for item in lst:p = ListNode()p.val = itemp.next = LL = preturn L
#打印linklist
def print_ll(ll):while True:if ll.val:print(ll.val)if ll.next==None: #尾插法停止点breakelif not ll.next: #头插法停止点breakll = ll.next
#题解
class Solution:def printListFromTailToHead(self, listNode):# write code hereres = []while(listNode):res.append(listNode.val)listNode=listNode.nextreturn res[3:0:-1]if __name__ == "__main__":lst = [1, 2, 3]linklist = creatlist_tail(lst)solution = Solution()res = solution.printListFromTailToHead(linklist)print(res)
结果
[3, 2, 1]
这篇关于【剑指offer】JZ6 从头到尾打印链表(Python)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!