class SingleLinkList(object): """单链表""" def __init__(self): self.__head = None
def is_empty(self): """判断链表是否为空""" return self.__head == None
def length(self): """链表⻓度""" # cur初始时指向头节点 cur = self.__head count = 0 # 尾节点指向None,当未到达尾部时 while cur != None: count += 1 # 将cur后移⼀个节点 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): """头部添加元素""" # 先创建⼀个保存item值的节点 node = SingleNode(item) # 将新节点的链接域next指向头节点,即_head指向的位置 node.next = self.__head # 将链表的头_head指向新节点 self.__head = node
def append(self, item): """尾部添加元素""" node = SingleNode(item) # 先判断链表是否为空,若是空链表,则将_head指向新节点 if self.is_empty(): self.__head = node # 若不为空,则找到尾部,将尾节点的next指向新节点 else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node
def insert(self, pos, item): """指定位置添加元素""" # 若指定位置pos为第⼀个元素之前,则执⾏头部插⼊ if pos <= 0: self.add(item) # 若指定位置超过链表尾部,则执⾏尾部插⼊ elif pos > (self.length()-1): self.append(item) # 找到指定位置 else: node = SingleNode(item) count = 0 # pre⽤来指向指定位置pos的前⼀个位置pos-1,初始从头节点开 始移动到指定位置 pre = self.__head while count < (pos-1): count += 1 pre = pre.next # 先将新节点node的next指向插⼊位置的节点 node.next = pre.next # 将插⼊位置的前⼀个节点的next指向新节点 pre.next = node
def remove(self,item): """删除节点""" cur = self.__head pre = None while cur != None: # 找到了指定元素
if cur.item == item: # 如果第⼀个就是删除的节点 if not pre: # 将头指针指向头节点的后⼀个节点 self.__head = cur.next else: # 将删除位置前⼀个节点的next指向删除位置的后⼀个 节点 pre.next = cur.next break else: # 继续按链表后移节点 pre = cur cur = cur.next
def search(self,item): """链表查找节点是否存在,并返回True或者False""" cur = self.__head while cur != None: if cur.item == item: return True cur = cur.next return False
if __name__ == "__main__": ll = SingleLinkList() ll.add(1) ll.add(2) ll.append(3) ll.insert(2, 4) print "length:",ll.length() ll.travel()
print ll.search(3) print ll.search(5) ll.remove(1) print "length:",ll.length() ll.travel()
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |