记得原来学数据结构和算法基础,觉得很难,现在用python实现数据结构太Easy了。
以下是练习的树结构和双向链表结构。
#tree class TreeNode: def __init__(self,value):#value is used here,node is used other places self.parent=None self.value=value self.children=[] def add_child(self,n): n.parent=self self.children.append(n) def digraph(self,g):#将树转换成networkx中的有向图。 if self.parent==None: g.add_node(self.value,level=0) for c in self.children: g.add_node(c.value,level=1) g.add_edge(self.value,c.value) c.digraph(g) def getroot(self): if self.parent==None: return self return self.parent.getroot() #double linkedlist class LinkedListNode(object): def __init__(self, value=None): self.prev = None self.next = None self.value = value def str_left(self): s=str(self.value) n=self.prev while n!=None: s+="->"+str(n.value) n=n.prev return s def str_right(self): s=str(self.value) n=self.next while n!=None: s+="->"+str(n.value) n=n.next return s def str(self): return self.head().str_right() def link_right(self,b): self.next=b b.prev=self def link_left(self,b): self.prev=b b.next=self def unlink_right(self): b=self.next self.next=None if b!=None: b.prev=None def unlink_left(self): b=self.prev self.prev=None if b!=None: b.next=None def head(self): if self.prev==None: return self else: return self.prev.head() def tail(self): if self.next==None: return self else: return self.next.tail() # def cut_prev(self): # before=self.prev # if before!=None: # else: # unlinkab(before,self) def remove_self(self): before=self.prev after=self.next self.unlink_left() self.unlink_right() if before!=None and after!=None: before.link_right(after)