首页 / 算法 / python数据结构与算法(7)
python数据结构与算法(7)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python数据结构与算法(7),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2200字,纯文字阅读大概需要4分钟。
内容图文
单链表的操作is_empty() 链表是否为空 length() 链表?度 travel() 遍历整个链表
add(item) 链表头部添加元素 append(item) 链表尾部添加元素 insert(pos, item) 指定位置添加元素 remove(item) 删除节点 search(item) 查找节点是否存在
单链表的实现
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[/size][/font]
[font=微软雅黑][size=3]
测试
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://blog.51cto.com/13517854/2323063
内容总结
以上是互联网集市为您收集整理的python数据结构与算法(7)全部内容,希望文章能够帮你解决python数据结构与算法(7)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。