赞
踩
1.定义一个结点类
val | next |
class ListNode: def __init__(self, x): self.val = x self.next = None
2.定义单链表 :(单链表是由一个一个结点构成)在结点类的基础上
class LinkList: #新建一个头指针为空的链表 def __init__(self): self.head=None #将数据插入链表: (这里必须要说的是最后返回链表的头指针) def initList(self, data): # 创建头结点 self.head = ListNode(data[0]) r=self.head p = self.head # 逐个为 data 内的数据创建结点, 建立链表 for i in data[1:]: node = ListNode(i) p.next = node p = p.next return r def printlist(self,head): if head == None: return node = head while node != None: print(node.val,end='') node = node.next
完整代码:
class ListNode: def __init__(self, x): self.val = x self.next = None class LinkList: def __init__(self): self.head=None def initList(self, data): # 创建头结点 self.head = ListNode(data[0]) r=self.head p = self.head # 逐个为 data 内的数据创建结点, 建立链表 for i in data[1:]: node = ListNode(i) p.next = node p = p.next return r def printlist(self,head): if head == None: return node = head while node != None: print(node.val,end='') node = node.next
if __name__ == '__main__': l=LinkList() data1 = [1, 2, 3] data2= [2, 4, 6] l1=l.initList(data1) l2=l.initList(data2) l.printlist(l1)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。