python实现数据结构单链表
Posted QZK
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现数据结构单链表相关的知识,希望对你有一定的参考价值。
#python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" def __init__(self, elem): self.elem = elem self.next = None # 节点一开始初始化的时候并不知道下一个元素的地址,所以先设置为空 class SingLinkList(object): """单链表""" def __init__(self, node=None): self.__head = node def is_empty(self): """"判断是否为空""" return self.__head == None def length(self): """返回长度""" # cur游标用来移动遍历节点 cur = self.__head # count 用来记录数量 count = 0 while cur != None: count += 1 cur = cur.next return count def travel(self): """遍历链表""" # cur游标用来移动遍历节点 cur = self.__head # count 用来记录数量 count = 0 while cur != None: print(cur.elem, end=‘ ‘) cur = cur.next print(‘ ‘) def add(self, item): """"链表头部添加""" node = Node(item) node.next = self.__head # 将新节点的next域指向首节点的头部 self.__head = node def append(self, item): """链表尾部添加""" node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node def insert(self, pos, item): """ 指定位置添加元素 :param pos: pos从0 开始 :param item: :return: """ if pos <= 0: self.add(item) elif pos > (self.length() - 1): self.append(item) else: pre = self.__head node = Node(item) count = 0 while count < (pos - 1): count += 1 pre = pre.next # 当循环退出后pre指向pos-1 node.next = pre.next pre.next = node def remove(self, item): """删除节点""" pre = None cur = self.__head while cur != None: if cur.elem == item: # 判断次节点是不是头节点 # 头结点: if cur == self.__head: self.__head = cur.next else: pre.next = cur.next break else: pre = cur cur = cur.next def search(self, item): """查找节点是否存在""" cur = self.__head while cur != None: if cur.elem == item: return True else: cur = cur.next return False if __name__ == ‘__main__‘: l = SingLinkList() print(l.is_empty()) l.add(0) l.append(1) l.add(8) print(l.length()) l.append(2) l.append(2) l.append(4) l.travel() l.insert(-1, 7) l.insert(2, 1) l.travel() l.remove(8) l.travel() # 后继节点:指的是下一个节点
以上是关于python实现数据结构单链表的主要内容,如果未能解决你的问题,请参考以下文章