def insert_value(self, val, loc=None): """ insert node to the list :param val: insert value :param loc: insert with index :return: """ if self.list_empty(): # if the list is empty self.head = Node(val, None) self.tail = self.head self.length = 1 else: if (not loc) | (loc == self.length): # if insert element without location or at the tail new_node = Node(val, None) self.tail.pnext = new_node self.tail = new_node self.length += 1 else: new_node = Node(val, None) last_node = self.head for index in range(self.length): if index == (loc - 1) - 1: break else: last_node = last_node.pnext next_node = last_node.pnext last_node.pnext = new_node new_node.pnext = next_node self.length += 1
def delete_value(self, loc=None): """ delete value from list :param loc: the location of list :return: """ if not self.list_empty(): if loc: last_node = self.head for index in range(self.length): if index == (loc - 1) - 1: break else: last_node = last_node.pnext next_node = last_node.pnext.pnext last_node.pnext = next_node else: now_node = self.head while now_node: if now_node.pnext.pnext is None: now_node.pnext = None break else: now_node = now_node.pnext self.length -= 1
判断链表是否为空
1 2 3 4 5 6 7 8 9
def list_empty(self): """ if the list is empty :return: """ if self.head is None: return True else: return False
打印链表内容
1 2 3 4 5 6 7 8 9 10 11
def list_traverse(self): """ visit all elements of the list :return: """ if not self.list_empty(): now_node = self.head print('-'*15) while now_node: print("value: ", now_node.value) now_node = now_node.pnext
测试案例
创建程序入口
1 2 3 4 5 6 7 8 9
if __name__ == "__main__": my_linkedlist = LinkedList() for i in range(5): my_linkedlist.insert_value(i) my_linkedlist.list_traverse() my_linkedlist.insert_value(['this', 'is', 'a', 'list'], 3) my_linkedlist.list_traverse() my_linkedlist.delete_value(2) my_linkedlist.list_traverse()