链表中的任意节点包括两部分,数据部分和链接到下一个节点的部分。
# 定义节点类 class Node(object): def __init__(self, data = None, next = None): self.data = data self.next = next class LinkedList(object): def __init__(self): self.head = Node() self.length = 0 def isEmpty(self): return self.length == 0 def append(self, value): node = Node(value) if self.isEmpty(): self.head.next = node self.length += 1 else: cur = self.head while cur.next is not None: cur = cur.next cur.next = node self.length += 1 def print_l(self): print(self.length) def travel(self): cur = self.head i = 1 while i <= self.length: print(cur.next.data) cur = cur.next i = i + 1 a = LinkedList() a.append(3) a.append(5) a.travel()