[DS+Algo] 003 一维表结构 Python 代码实现
- 接上一篇
 
前言
- 本篇共 3 个代码实现
 - 严格来说
code1相当于模仿了 Python 的 list 的部分简单功能code2与code3简单实现了“循环单链表”与“双链表”
 - 代码比较简单,但它们的行数相比于普通博文又显得有些长,所以单独写一篇
 - 其实放到 GitHub 上更合适,我打算积几个再去 push
 
1. 模仿 Python 的 list 的一些功能
class SingleNode(object):
    def __init__(self, item):
        self.item = item
        self.next = None
class SingleLinkList(object):
    def __init__(self):
        self._head = None
    def is_empty(self):
        return self._head is None
    def length(self):
        cur = self._head
        count = 0
        while cur is not None:
            count += 1
            cur = cur.next
        return count
    def traverse(self):
        cur = self._head
        while cur:
            print(cur.item)
            cur = cur.next
        return None
    def add_first(self, item):
        node = SingleNode(item)
        node.next = self._head
        self._head = node
    def append(self, item):
        node = SingleNode(item)
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next:
                cur = cur.next
            cur.next = node
    def insert(self, pos, item):
        if pos <= 0:
            self.add_first(item)
        elif (self.length() - 1) < pos:
            self.append(item)
        else:
            node = SingleNode(item)
            count = 0
            pre = self._head
            while count < (pos - 1):
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node
    def remove(self, item):
        cur = self._head
        pre = None
        while cur:
            if cur.item == item:
                if not pre:
                    self._head = cur.next
                else:
                    pre.next = cur.next
                break
            else:
                pre = cur
                cur = cur.next
    def search(self, item):
        cur = self._head
        while cur:
            if cur.item == item:
                return True
            cur = cur.next
        return False
if __name__ == "__main__":
    lst = SingleLinkList()
    lst.add_first(10)
    lst.add_first(20)
    lst.append(30)
    lst.insert(2, 40)
    print(f"Length of lst is {lst.length()}")
    lst.traverse()
    print(lst.search(30))
    print(lst.search(31))
    lst.remove(20)
    print(f"Length of lst is {lst.length()}")
    lst.traverse()
2. 循环单链表
class SingleNode(object):
    def __init__(self, item):
        self.item = item
        self.next = None
class SingleCycLinkedList(object):
    def __init__(self):
        self._head = None
    def is_empty(self):
        return self._head is None
    def length(self):
        if self.is_empty():
            return 0
        cnt = 1
        cur = self._head
        while cur.next != self._head:
            cur = cur.next
            cnt += 1
        return cnt
    def traverse(self):
        if self.is_empty():
            return
        cur = self._head
        print(cur.item)
        while cur.next != self._head:
            cur = cur.next
            print(cur.item)
    def add_first(self, item):
        node = SingleNode(item)
        if self.is_empty():
            self._head = node
            node.next = self._head
        else:
            node.next = self._head
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            cur.next = node
            self._head = node
    def append(self, item):
        node = SingleNode(item)
        if self.is_empty():
            self._head = node
            node.next = self._head
        else:
            cur = self._head
            while cur.next != self._head:
                cur = cur.next
            cur.next = node
            node.next = self._head
    def insert(self, pos, item):
        if pos <= 0:
            self.add_first(item)
        elif self.length() - 1 < pos:
            self.append(item)
        else:
            node = SingleNode(item)
            cur = self._head
            cnt = 0
            while cnt < pos - 1:
                cur = cur.next
                cnt += 1
            node.next = cur.next
            cur.next = node
    def remove(self, item):
        if self.is_empty():
            return
        cur = self._head
        pre = None
        if cur.item == item:
            if cur.next != self._head:
                while cur.next != self._head:
                    cur = cur.next
                cur.next = self._head.next
                self._head = self._head.next
            else:
                self._head = None
        else:
            pre = self._head
            while cur.next != self._head:
                if cur.item == item:
                    pre.next = cur.next
                    return
                else:
                    pre = cur
                    cur = cur.next
            if cur.item == item:
                pre.next = cur.next
    def search(self, item):
        if self.is_empty():
            return False
        cur = self._head
        if cur.item == item:
            return True
        while cur.next != self._head:
            cur = cur.next
            if cur.item == item:
                return True
        return False
if __name__ == "__main__":
    lst = SingleCycLinkedList()
    lst.add_first(2)
    lst.add_first(1)
    lst.append(4)
    lst.append(5)
    lst.insert(0, 0)
    lst.insert(3, 33)
    print(f"length: {lst.length()}")
    lst.traverse()
    print(lst.search(3))
    print(lst.search(5))
    lst.remove(33)
    print(f"length: {lst.length()}")
    lst.traverse()
3. 双链表
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 is None
    def length(self):
        cur = self._head
        cnt = 0
        while cur:
            cnt += 1
            cur = cur.next
        return cnt
    def traverse(self):
        cur = self._head
        while cur:
            print(cur.item)
            cur = cur.next
    def add_first(self, item):
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            node.next = self._head
            self._head.prev = node
            self._head = node
    def append(self, item):
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            cur = self._head
            while cur.next:
                cur = cur.next
            cur.next = node
            node.prev = cur
    def search(self, item):
        cur = self._head
        while cur:
            if cur.item == item:
                return True
            cur = cur.next
        return False
    def insert(self, pos, item):
        if pos <= 0:
            self.add_first(item)
        elif self.length() - 1 < pos:
            self.append(item)
        else:
            node = Node(item)
            cur = self._head
            cnt = 0
            while cnt < pos - 1:
                cur = cur.next
                cnt += 1
            node.prev = cur
            node.next = cur.next
            cur.next.prev = node
            cur.next = node
    def remove(self, item):
        if self.is_empty():
            return
        else:
            cur = self._head
            if cur.item == item:
                if cur.next is None:
                    self._head = None
                else:
                    cur.next.prev = None
                    self._head = cur.next
                return
            cur = cur.next
            while cur:
                if cur.item == item:
                    cur.prev.next = cur.next
                    cur.next.prev = cur.prev
                    break
                cur = cur.next
if __name__ == "__main__":
    lst = DLinkList()
    lst.add_first(2)
    lst.add_first(1)
    lst.append(4)
    lst.append(5)
    lst.insert(0, 0)
    lst.insert(3, 33)
    print(f"length: {lst.length()}")
    lst.traverse()
    print(lst.search(3))
    print(lst.search(5))
    lst.remove(33)
    print(f"length: {lst.length()}")
    lst.traverse()
												
											[DS+Algo] 003 一维表结构 Python 代码实现的更多相关文章
- [DS+Algo] 002 一维表结构
		
目录 1. 顺序表 1.1 分类 1.2 实现方式 1.3 扩容问题 1.4 操作 2. 链表 2.1 分类 2.2 链表相关操作 2.3 链表 VS 顺序表 3. 关于代码实现 1. 顺序表 1.1 ...
 - [DS+Algo] 004 栈、队列及其代码实现
		
1. Stack FILO (FirstInLastOut) 的链表结构 在程序编译环境上使用较多 常用操作 push pop peek is_empty size Python 代码示例 class ...
 - 一段关于用户登录 和乘法表的python代码
		
用户登录代码(低配): name = 1password =11counter = 1while counter <3 : a = int(input ('name:')) #注意这里 inpu ...
 - python 全栈开发,Day105(路飞其他数据库表结构,立即结算需求)
		
考试第三部分:Django 16. 列列举你熟悉的Http协议头以及作用.(1分) Accept-Charset: 用于告诉浏览器,客户机采用的编码 Host: 客户机通过这个头告诉服务器,想访问的 ...
 - python 全栈开发,Day98(路飞学城背景,django ContentType组件,表结构讲解)
		
昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确. - API (IOS,安卓,PC,微信小程序...) - vue.js等框架编写前端时,会比之前写jQuery ...
 - DS实验题 Old_Driver UnionFindSet结构 指针实现邻接表存储
		
题目见前文:DS实验题 Old_Driver UnionFindSet结构 这里使用邻接表存储敌人之间的关系,邻接表用指针实现: // // main.cpp // Old_Driver3 // // ...
 - 开源一个适用iOS的数据库表结构更新机制的代码
		
将前段时间开源的代码.公布一下: ARDBConfig On the iOS, provide a database table structure update mechanism, ensure ...
 - 【转】Informix数据表结构分析资料整理之约束查询代码
		
原文地址:http://blog.csdn.net/xqf222/article/details/6271219 本文主要整理了Informix数据库相关系统表数据,已分析整个Informix数据表结 ...
 - Python SQLAlchemy多对多外键关联时表结构
		
# 创建多对多表结构 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine import cre ...
 
随机推荐
- ZROI 19.08.12模拟赛
			
传送门 写在前面:为了保护正睿题目版权,这里不放题面,只写题解. "我发现问题的根源是大家都不会前缀和."--敦爷 A 敦爷spj写错了,差点把蒟蒻swk送走 \(50pts:\) ...
 - 【NOIP2016提高A组五校联考4】label
			
题目 题目 20%算法 设\(f_{i,j}\)表示第i个节点选了j这个权值的方案数. 显然转移方程为,\[f_{i,j}=\Pi_{v=son(i)}(\sum_{k=1}^{j-k}f_{v,k} ...
 - 【NOIP2016提高A组模拟8.17】(雅礼联考day1)Binary
			
题目 分析 首先每个数对\(2^i\)取模.也就是把每个数的第i位以后删去. 把它们放进树状数组里面. 那么当查询操作, 答案就位于区间\([2^i-x,2^{i-1}-1-x]\)中,直接查询就可以 ...
 - EF大数据插入
			
_April给出代码: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotati ...
 - 【javascript】生成二维码
			
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 < ...
 - 【技术分享:python 应用之三】使用 python 修改 excel 表格的 sheet 名称
			
原始需求:已经下载好了 Excel 文件,但是 Excel 里的 sheet 的名称想要修改一下,比如原本默认的是sheet1,需要修成“DNEWCD_JQJSHMX”.需求比较简单,直接上代码吧! ...
 - VS Code报错Module 'xx' has no 'xx' member pylint(no-member)解决办法
			
pylint是vscode的python语法检查器,pylint是静态检查,在用第三方库的时候有些成员只有在运行代码的时候才会被建立,它就找不到成员,在设置(settings.json)里添加 &qu ...
 - Linux安装配置redis 、启动redis、redis设置密码
			
由于间隔时间较长.机器的环境不同等等原因,所以每次安装redis的时候总是不那么顺利,所以这次我要做个笔记 文章大部分内容源于https://blog.csdn.net/gisredevelopmen ...
 - vue之Object.defineProperty()
			
了解Object.defineProerty()方法 关于Object.defineProperty()方法的解释,理解Object.defineProperty的作用 这篇文章做了很详细的概述 关于 ...
 - SVG相关学习(一)SVG基础
			
SVG 相关学习 SVG SVG 指可伸缩矢量图形 (Scalable Vector Graphics) SVG viewBox <svg width="500" heigh ...