python实现数据结构中双向循环链表操作的示例
看此博客之前建议先看看B站的视频python数据结构与算法系列课程,该课程中未实现双向循环链表的操作,所以我按照该视频的链表思路实现了双向循环链表的操作,欢迎大家阅读与交流,如有侵权,请联系博主!
下面附上代码:
classNode: def__init__(self,elem): self.elem=elem self.prev=None self.next=None classDoubleCycleLinkList: def__init__(self,node=None): self.__head=node defis_empty(self): """判空""" ifself.__headisNone: returnTrue returnFalse deflength(self): """链表长度""" ifself.is_empty(): return0 cur=self.__head count=1 whilecur.nextisnotself.__head: count+=1 cur=cur.next returncount deftravel(self): """遍历链表""" ifself.is_empty(): return cur=self.__head whilecur.nextisnotself.__head: print(cur.elem,end="") cur=cur.next print(cur.elem,end="") print("") defadd(self,elem): """头插法""" node=Node(elem) ifself.is_empty(): self.__head=node node.prev=node node.next=node else: self.__head.prev.next=node node.prev=self.__head.prev node.next=self.__head self.__head.prev=node self.__head=node defappend(self,elem): """尾插法""" node=Node(elem) ifself.is_empty(): self.__head=node node.prev=node node.next=node else: node.next=self.__head node.prev=self.__head.prev self.__head.prev.next=node self.__head.prev=node definsert(self,pos,elem): """任一位置(pos)插入,下标从0数起""" ifpos<=0: self.add(elem) elifpos>(self.length()-1): self.append(elem) else: count=0 cur=self.__head node=Node(elem) whilecount<(pos-1): count+=1 cur=cur.next node.next=cur.next node.prev=cur node.next.prev=node cur.next=node defremove(self,elem): """删除某一节点,若有多个符合条件的节点,删除第一个即可""" ifself.is_empty(): return cur=self.__head whilecur.nextisnotself.__head: ifcur.elem==elem: ifcurisself.__head: self.__head=cur.next cur.prev.next=cur.next cur.next.prev=cur.prev else: cur.prev.next=cur.next cur.next.prev=cur.prev break cur=cur.next ifcur.elem==elem: cur.prev.next=self.__head self.head=cur.prev defsearch(self,elem): """查找某一个节点""" ifself.is_empty(): returnFalse cur=self.__head whilecur.nextisnotself.__head: ifcur.elem==elem: returnTrue cur=cur.next #while中处理不到尾节点,所以进行最后尾节点的判断 ifcur.elem==elem: returnTrue returnFalse
到此这篇关于python实现数据结构中双向循环链表操作的示例的文章就介绍到这了,更多相关python双向循环链表操作内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!