python: 單鏈表
阿新 • • 發佈:2018-12-21
class Node: def __init__(self, data, next=None): self.data = data self.next = next def __str__(self): return str(self.data) class LList: def __init__(self): self.head = None def is_empty(self): return self.head is None def prepend(self, data): self.head = Node(data, self.head) def pop(self): if self.head is None: raise ValueError("linklist is empty") e = self.head.data self.head = self.head.next return e def pop_last(self): if self.head is None: raise ValueError("linklist is empty") p = self.head if p.next is None: e = p.data self.head = None return e while p.next.next is not None: p = p.next e = p.next.data p.next = None return e # def find(self, pred): # p = self.head def append(self, data): if self.head is None: self.head = Node(data) return p = self.head while p.next is not None: p = p.next p.next = Node(data) def printAll(self): p = self.head while p is not None: print(p.data, end='') if p.next is not None: print(', ', end='') p = p.next print('') # l1 = LList() # for i in range(3): # l1.prepend(i) # for i in range(3, 5): # l1.append(i) # l1.printAll()