标签:ges ret ado src type app 查找 空值 顺序
链表与顺序表的对?双向链表
?种更复杂的链表是“双向链表”或“双?链表”。每个节点有两个链接:?个指 向前?个节点,当此节点为第?个节点时,指向空值;?另?个指向下?个 节点,当此节点为最后?个节点时,指向空值。
操作
is_empty() 链表是否为空 length() 链表?度 travel() 遍历链表 add(item) 链表头部添加 append(item) 链表尾部添加 insert(pos, item) 指定位置添加 remove(item) 删除节点 search(item) 查找节点是否存在
实现
class Node(object): """双向链表节点""" def __init__(self, item): self.item = item self.next = None self.prev = None
class DLinkList(object): """双向链表""" def __init__(self): self.__head = None
def is_empty(self): """判断链表是否为空""" return self.__head == None
def length(self): """返回链表的?度""" cur = self.__head count = 0 while cur != None: count += 1 cur = cur.next return count
def travel(self): """遍历链表""" cur = self.__head while cur != None: print cur.item, cur = cur.next print ""
def add(self, item): """头部插?元素""" node = Node(item) if self.is_empty(): # 如果是空链表,将_head指向node self.__head = node else: # 将node的next指向_head的头节点 node.next = self.__head # 将_head的头节点的prev指向node
self.__head.prev = node # 将_head 指向node self.__head = node
def append(self, item): """尾部插?元素""" node = Node(item) if self.is_empty(): # 如果是空链表,将_head指向node self.__head = node else: # 移动到链表尾部 cur = self.__head while cur.next != None: cur = cur.next # 将尾节点cur的next指向node cur.next = node # 将node的prev指向cur node.prev = cur
def search(self, item): """查找元素是否存在""" cur = self.__head while cur != None: if cur.item == item: return True cur = cur.next return False
标签:ges ret ado src type app 查找 空值 顺序
原文地址:http://blog.51cto.com/13517854/2323067