def insert(self, data, pos=0): if pos <= 0: self.add(data) elif pos > self.size() - 1: self.append(data) else: newNode = Node(data) preHead = self.__head count = 0 # preHead指向指定位置前一个位置pos-1 while count < pos - 1: count += 1 preHead = preHead.getNext() # 新节点的指针域指向插入位置的节点 newNode.setNext(preHead.getNext()) # 插入位置前一个节点的指针域指向新节点 preHead.setNext(newNode)
def append(self, data): newNode = Node(data) if self.isEmpty(): self.__head = newNode else: currentHead = self.__head while currentHead.getNext() is not None: currentHead = currentHead.getNext() currentHead.setNext(newNode)
def add(self, data): newNode = Node(data) if self.isEmpty(): self.__head = newNode newNode.setNext(self.__head) else: # 创建新节点,其指针域指向头节点 newNode = Node(data, nextp=self.__head) currentHead = self.__head while currentHead.getNext() is not self.__head: currentHead = currentHead.getNext() # 尾节点指向新节点 currentHead.setNext(newNode) self.__head = newNode
# preOrder = N L R # inOrder = L K R # postOrder = L R N def size(root): if root is None: return 0 i = size(root.left) j = size(root.right) sum = i + j + 1 return sum root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(6) root.right.right = Node(7) root.left.left = Node(4) root.left.right = Node(5) print(size(root))
def push(self, data): newNode = Node(data, nextp=self.__head) self.__head = newNode self.__count += 1
def add(self, data): # 创建新节点,其指针域指向头节点 newNode = Node(data, nextp=self.__head) # 头节点指向新节点 self.__head = newNode