数据结构:链表(python版)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Minion Xu class LinkedListUnderflow(ValueError):
pass class LNode(object):
def __init__(self, elem, next_=None):
self.elem = elem
self.next = next_ class LList(object):
def __init__(self):
self._head = None
self._num = 0 #清楚单链表
def clear(self):
LList.__init__(self) #判断单链表是否为空
def is_empty(self):
return self._head is None #计算单链表元素的个数 两种方式:遍历列表 或 返回 _num
def count(self):
return self._num
"""
p = self._head
num = 0
while p:
num += 1
p = p.next
return num
"""
def __len__(self):
p = self._head
num = 0
while p:
num += 1
p = p.next
return num #表首端插入元素
def prepend(self, elem):
self._head = LNode(elem, self._head)
self._num += 1 #删除表首端元素
def pop(self):
if self._head is None:
raise LinkedListUnderflow("in pop")
e = self._head.elem
self._head = self._head.next
self._num -= 1
return e #表末端插入元素
def append(self, elem):
if self._head is None:
self._head = LNode(elem)
self._num += 1
return
p = self._head
while p.next:
p = p.next
p.next = LNode(elem)
self._num += 1 #删除表末端元素
def pop_last(self):
if self._head is None:
raise LinkedListUnderflow("in pop_last")
p = self._head
#表中只有一个元素
if p.next is None:
e = p.elem
self._head = None
self._num -= 1
return e
while p.next.next:
p = p.next
e = p.next.elem
p.next = None
self._num -= 1
return e #发现满足条件的第一个表元素
def find(self, pred):
p = self._head
while p:
if pred(p.elem):
return p.elem
p = p.next #发现满足条件的所有元素
def filter(self, pred):
p = self._head
while p:
if pred(p.elem):
yield p.elem
p = p.next #打印显示
def printall(self):
p = self._head
while p:
print(p.elem, end="")
if p.next:
print(", ",end="")
p = p.next
print("") #查找某个值,列表有的话返回为True,没有的话返回False
def search(self, elem):
p = self._head
foundelem = False
while p and not foundelem:
if p.elem == elem:
foundelem = True
else:
p = p.next
return foundelem #找出元素第一次出现时的位置
def index(self, elem):
p = self._head
num = -1
found = False
while p and not found:
num += 1
if p.elem == elem:
found = True
else:
p = p.next
if found:
return num
else:
raise ValueError("%d is not in the list!" % elem) #删除第一个出现的elem
def remove(self, elem):
p = self._head
pre = None
while p:
if p.elem == elem:
if not pre:
self._head = p.next
else:
pre.next = p.next
break
else:
pre = p
p = p.next
self._num -= 1 #在指定位置插入值
def insert(self, pos, elem):
#当值大于count时就默认尾端插入
if pos >= self.count():
self.append(elem)
#其他情况
elif 0<=pos<self.count():
p = self._head
pre = None
num = -1
while p:
num += 1
if pos == num:
if not pre:
self._head = LNode(elem, self._head)
self._num += 1
else:
pre.next = LNode(elem,pre.next)
self._num += 1
break
else:
pre = p
p = p.next
else:
raise IndexError #删除表中第i个元素
def __delitem__(self, key):
if key == len(self) - 1:
#pop_lasy num自减
self.pop_last()
elif 0<=key<len(self)-1:
p = self._head
pre = None
num = -1
while p:
num += 1
if num == key:
if not pre:
self._head = pre.next
self._num -= 1
else:
pre.next = p.next
self._num -=1
break
else:
pre = p
p = p.next
else:
raise IndexError #根据索引获得该位置的元素
def __getitem__(self, key):
if not isinstance(key, int):
raise TypeError
if 0<=key<len(self):
p = self._head
num = -1
while p:
num += 1
if key == num:
return p.elem
else:
p = p.next
else:
raise IndexError # ==
def __eq__(self, other):
#两个都为空列表 则相等
if len(self)==0 and len(other)==0:
return True
#两个列表元素个数相等 当每个元素都相等的情况下 两个列表相等
elif len(self) == len(other):
for i in range(len(self)):
if self[i] == other[i]:
pass
else:
return False
#全部遍历完后则两个列表相等
return True
#两个列表元素个数不相等 返回Fasle
else:
return False
# !=
def __ne__(self, other):
if self.__eq__(other):
return False
else:
return True
# >
def __gt__(self, other):
l1 = len(self)
l2 = len(other)
if not isinstance(other, LList):
raise TypeError
# 1.len(self) = len(other)
if l1 == l2:
for i in range(l1):
if self[i] == other[i]:
continue
elif self[i] < other[i]:
return False
else:
return True
#遍历完都相等的话说明两个列表相等 所以返回False
return False
# 2.len(self) > len(other)
if l1 > l2:
for i in range(l2):
if self[i] == other[i]:
continue
elif self[i] < other[i]:
return False
else:
return True
#遍历完后前面的元素全部相等 则列表个数多的一方大
#if self[l2-1] == other[l2-1]:
return True
# 3.len(self) < len(other)
if l1 < l2:
for i in range(l1):
if self[i] == other[i]:
continue
elif self[i] < other[i]:
return False
else:
return True
#遍历完后前面的元素全部相等 则列表个数多的一方大
#if self[l2-1] == other[l2-1]:
return False
# <
def __lt__(self, other):
#列表相等情况下>会返回False,则<这里判断会返回True,有错误.所以要考虑在==的情况下也为False
if self.__gt__(other) or self.__eq__(other):
return False
else:
return True
# >=
def __ge__(self, other):
"""
if self.__eq__(other) or self.__gt__(other):
return True
else:
return False
"""
#大于等于和小于是完全相反的,所以可以依靠小于实现
if self.__lt__(other):
return False
else:
return True
# <=
def __le__(self, other):
"""
if self.__eq__(other) or self.__lt__(other):
return True
else:
return False
"""
##小于等于和大于是完全相反的,所以可以依靠大于实现
if self.__gt__(other):
return False
else:
return True #example 大于5返回True的函数
def greater_5(n):
if n>5:
return True if __name__=="__main__":
mlist1 = LList()
mlist2 = LList()
mlist1.append(1)
mlist2.append(1)
mlist1.append(2)
mlist2.append(2)
#mlist1.append(2)
mlist2.append(6)
mlist2.append(11)
mlist2.append(12)
mlist2.append(14)
mlist1.printall()
mlist2.printall()
#print(mlist1 == mlist2)
#print(mlist1 != mlist2)
print(mlist1 <= mlist2) mlist2.del_if(greater_5)
mlist2.printall() """
llist1 = LNode(1)
p = llist1
for i in range(2,11):
p.next = LNode(i)
p = p.next p = llist1
while p is not None:
print(p.elem, end=" ")
p = p.next
print("\n=====") mlist1 = LList()
for i in range(10):
mlist1.prepend(i)
for i in range(11,20):
mlist1.append(i)
mlist1.printall() mlist1.pop()
mlist1.printall() mlist1.pop_last()
mlist1.printall() print("===")
print(mlist1.search(18)) print(mlist1.index(18)) mlist1.remove(0)
mlist1.printall() mlist1.insert(1,20)
mlist1.printall() del(mlist1[2])
mlist1.printall() print(mlist1.count()) print(mlist1.count()) -
print(len(mlist1))
print(mlist1.find(greater_5))
for i in mlist1.filter(greater_5):
print(i, end=",")
"""
数据结构:链表(python版)的更多相关文章
- 数据结构之队列(Python 版)
数据结构之队列(Python 版) 队列的特点:先进先出(FIFO) 使用链表技术实现 使用单链表技术,在表首尾两端分别加入指针,就很容易实现队列类. 使用顺序表list实现 # 队列类的实现 cla ...
- 数据结构之 栈 (Python 版)
数据结构之 栈 (Python 版) -- 利用线性表实现栈 栈的特性: 后进先出 基于顺序表实现栈 class SStack(): ''' 基于顺序表 实现的 栈类 ''' def __init__ ...
- 数据结构之线性表(python版)
数据结构之线性表(python版) 单链表 1.1 定义表节点 # 定义表节点 class LNode(): def __init__(self,elem,next = None): self.el ...
- 数据结构C语言版 有向图的十字链表存储表示和实现
/*1wangxiaobo@163.com 数据结构C语言版 有向图的十字链表存储表示和实现 P165 编译环境:Dev-C++ 4.9.9.2 */ #include <stdio.h> ...
- Python—数据结构——链表
数据结构——链表 一.简介 链表是一种物理存储上非连续,数据元素的逻辑顺序通过链表中的指针链接次序,实现的一种线性存储结构.由一系列节点组成的元素集合.每个节点包含两部分,数据域item和指向下一个节 ...
- 北京大学公开课《数据结构与算法Python版》
之前我分享过一个数据结构与算法的课程,很多小伙伴私信我问有没有Python版. 看了一些公开课后,今天特向大家推荐北京大学的这门课程:<数据结构与算法Python版>. 课程概述 很多同学 ...
- 【数据结构与算法Python版学习笔记】引言
学习来源 北京大学-数据结构与算法Python版 目标 了解计算机科学.程序设计和问题解决的基本概念 计算机科学是对问题本身.问题的解决.以及问题求解过程中得出的解决方案的研究.面对一 个特定问题,计 ...
- 数据结构:顺序表(python版)
顺序表python版的实现(部分功能未实现) #!/usr/bin/env python # -*- coding:utf-8 -*- class SeqList(object): def __ini ...
- Python3玩转单链表——逆转单向链表pythonic版
[本文出自天外归云的博客园] 链表是由节点构成的,一个指针代表一个方向,如果一个构成链表的节点都只包含一个指针,那么这个链表就是单向链表. 单向链表中的节点不光有代表方向的指针变量,也有值变量.所以我 ...
- 线性表应用--Josephus问题的解法(Python 版)
线性表应用 --Josephus问题的解法(Python 版) Josephus问题描述:假设有n个人围坐一圈,现在要求从第k个人开始报数,报到第m个数的人退出.然后从下一个人开始继续报数并按照相同的 ...
随机推荐
- Sharing A Powerful Tool For Application Auto Monitor
本文分享的这个应用监控小工具,本来是我在五年多以前开发实现的windows服务监控的一个windows服务.听上去比较拗口吧,是的,这个应用一开始就是个监控windows服务的windows服务. 记 ...
- EF连接PostgreSql
1.用nuget安装npgsql和EF 注意,Nuget一定要安装Npgsql的2.2.7版本,更高版本nuget在后面安装EF的时候无法自动解析. install-Package Npgsql -V ...
- [CORS:跨域资源共享] W3C的CORS Specification
随着Web开放的程度越来越高,通过浏览器跨域获取资源的需求已经变得非常普遍.在我看来,如果Web API不能针对浏览器提供跨域资源共享的能力,它甚至就不应该被称为Web API.从另一方面来看,浏览器 ...
- 考勤系统——代码分析datagrid
datagrid是easyui的控件,DataGrid以表格形式展示数据,并提供了丰富的选择.排序.分组和编辑数据的功能支持.DataGrid的设计用于缩短开发时间,并且使开发人员不需要具备特定的知识 ...
- python守护线程
如果你设置一个线程为守护线程,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出.如果你的主线程在退出的时候,不用等待那些子线程完成,那就设置这些线程的daemon属性.即在线程开 ...
- 【WP开发】加密篇:单向加密
单向加密,简单地说就是对数据进行哈希处理,平时我们见得较多的有MD5.SHA1等,都属于单向加密.上一篇文章中,老周跟大家扯了有关双向加密的事,本文咱们就扯一下单向加密吧. 要对数据进行哈希处理也不是 ...
- SQL联合主键 查重
2014年最后一天,今天在给数据库导入数据的时候,遇到一个问题,就是联合主键去重. 事情是这样的,现有一个表M,我想找个表中导入了许多数据,并需要将字段A(int)和B(int)联合设置为主键. 但是 ...
- Hawk: 无编程抓取淘女郎的所有高清照片
1.这是什么鬼? 哦?美女? 最近看了这一篇文章:http://cuiqingcai.com/1001.html 大概说的是用Python和Pyspider(这货好像是我的一位师兄写的,吓尿),抓取淘 ...
- MVC, MVP, MVVM比较以及区别(下)
上一篇得到大家的关注,非常感谢.一些朋友评论中,希望快点出下一篇.由于自己对于这些模式的理解也是有限,所以这一篇来得迟了一些.对于这些模式的比较,是结合自己的理解,一些地方不一定准确,但是只有亮出自己 ...
- php+phpStorm+xdebug配置方法
1.下载xdebug文件 http://xdebug.org/wizard.php 将phpinfo()的源代码复制到文本框中,xdebug会提示如何配置和下载哪个版本的xdebug. 全部下载地址: ...