python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】
Python  /  管理员 发布于 7年前   435
本文实例讲述了python单向链表的基本实现与使用方法。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*-#! python3class Node(): def __init__(self,item): #初始化这个节点,值和下一个指向 self.item = item self.next = Noneclass SingleLinklist(): def __init__(self): #初始化这个单链表的头指针为空 self._head = None def length(self): #获取这个链表的长度 count = 0 cur = self._head while cur != None: count+=1 cur = cur.next return count def is_empty(self): """判断是否为空""" return self._head == None def add(self,item): """在头部添加元素""" node = Node(item) node.next = self._head self._head = node def append(self,item): """在尾部添加元素""" cur = self._head node = Node(item) while cur != None: cur = cur.next cur.next = node def insert(self,pos,item): """在选定的位置添加元素""" cur = self._head node = Node(item) count = 0 if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: while count < (pos -1): count+=1 cur = cur.next node.next = cur.next cur.next = node def travel(self): """遍历整个链表""" cur = self._head while cur != None: print(cur.item,end=" ") cur = cur.next print(" ") def remove(self,item): """删除链表""" cur = self._head pre =None while cur != None: if cur.item == item: if not pre: self._head = cur.next break else: pre.next = cur.next else: pre = cur # cur = cur.next def search(self,item): """查找某个节点""" cur = self._head while cur != None: if cur.item == item: print("找到这个元素了") return True cur = cur.next print("抱歉没有这个元素") return Falsesinglistdemo = SingleLinklist()singlistdemo.add(1)singlistdemo.add(2)singlistdemo.add(65)singlistdemo.insert(2,77)singlistdemo.insert(1,66)singlistdemo.insert(0,66)print(singlistdemo.length())singlistdemo.travel()singlistdemo.remove(1)singlistdemo.travel()singlistdemo.search(65)
运行结果:
6
66 65 66 2 77 1
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号