用Python实现链表Linklist
在leetcode上面试着用Python解题,但是遇到链表、二叉树什么的,Python就用不溜。在网上看了一些资料。
完整的实现过程如下:class Node: next = None data = None def __init__(self, nodeData): self.data = nodeData# 一个链表数据结构,包括一个 根节点root 还有 链表大小sizeclass LinkList: root = None size = 0; def __init__(self): self.root = None size = 0 def __del__(self): "删除链表(清空节点)" if self.root is None: return curNode = self.root while curNode.next is not None: tempNode = curNode curNode = curNode.next tempNode = None curNode = None # Insert a new node to the LinkList def Insert(self, newData): "添加节点" newNode = Node(newData) # 每次都新建一个Node(新地址) if self.root is None: self.root = newNode self.size = 1 return tempNode = self.root while tempNode.next is not None: tempNode = tempNode.next tempNode.next = newNode self.size += 1 # def Get data of Position pos def GetData(self, pos): if pos >= self.size or pos < 0: return None else: tempNode = self.root for i in range(0, pos): tempNode = tempNode.next return tempNode.data # Remove a certain node def Remove(self, theData): curNode = self.root if curNode is None: return if self.size == 1 and curNode.data == theData: curNode.data = None curNode = None self.size -= 1 return elif curNode.data == theData: # 第一个节点就是需要删除的节点 self.root = curNode.next curNode = None self.size -= 1 return while curNode.next is not None: if curNode.next.data == theData: tempNode = curNode.next curNode.next = curNode.next.next tempNode = None # remove the node,but curNode stays still self.size -= 1 else: curNode = curNode.next # Get Root Node def GetRoot(self): return self.root # def Get Size def GetSize(self): return self.size # print the data of the LinkList def Print(self): tempNode = self.root while tempNode is not None: print tempNode.data, tempNode = tempNode.next if __name__ == '__main__': print ("start main()") mylist = LinkList() # 一个LinkList 就是一个完整的链表; Node 为链表的节点 print mylist.GetSize() for i in range(1, 10): mylist.Insert(i) print ('输出该单链表:') mylist.Print() print ("\n mylist 的 size:%s" % mylist.GetSize()) print ("---------------------------------\n删除1号索引的元素:") mylist.Remove(6) mylist.Remove(1) print ("输出删除1号索引后链表的元素:\n") mylist.Print() print ("\n删除后的元素个数:%s" % mylist.GetSize())
参考: