1.链表的定义

如图:

注意:

(1)线性表包括顺序表和链表

(2)顺序表是将元素顺序地存放在一块连续的存储区里

(3)链表是将元素存放在通过链构造的存储快中

2. 单向链表的实现

#!/usr/bin/env python
# _*_ coding:UTF-8 _*_

class Node(object):

    def __init__(self, elem):
        self.elem = elem
        self.next = None

class SingleLinkList(object):
    '''单向链表'''
    def __init__(self, node=None):
        self.__head = node

    def add(self, item):
        '''向单向链表的头部添加元素'''
        node = Node(item)
        node.next = self.__head
        self.__head = node
        return True

    def insert(self, pos, item):
        '''向单向链表指定位置插入元素'''
        if pos <= 0:
            self.add(item)
        elif pos > self.length() -1:
            self.append(item)
        else:
            pre = self.__head
            count = 0
            while pos - 1 > count:
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node
        return True

    def append(self, item):
        '''向单向链表的尾部追加元素'''
        node = Node(item)
        cur = self.__head
        while cur != None:
            if cur.next != None:
                cur = cur.next
            else:
                break
        cur.next = node
        return True

    def remove(self, item):
        '''删除元素'''
        pre = None
        cur = self.__head
        while cur != None:
            if cur.elem == item:
                if pre != None:
                    pre.next = cur.next
                else:
                    self.__head = cur.next
                break
            else:
                pre = cur
                cur = cur.next
        return False

    def search(self, item):
        '''指定元素搜索'''
        cur = self.__head
        index = 0
        while cur != None:
            if cur.elem != item:
                cur = cur.next
                index += 1
            else:
                return index
        return -1

    def travel(self):
        '''遍历打印单向链表的值'''
        cur = self.__head
        str = ''
        while cur != None and cur.elem != None:
            str += '%s' % cur.elem
            cur = cur.next
        return str

    def length(self):
        '''返回单向链表的长度'''
        cur = self.__head
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

    def is_empty(self):
        return self.__head == None

if __name__ == "__main__":
    singleLinkList = SingleLinkList()
    print singleLinkList.is_empty()
    print singleLinkList.length()

    singleLinkList.add(1)
    singleLinkList.insert(0, 2)
    singleLinkList.append(3)

    print singleLinkList.is_empty()
    print singleLinkList.length()

    print singleLinkList.travel()
    print singleLinkList.search(3)

    singleLinkList.remove(2)
    print singleLinkList.travel()

结果如下:

/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/bat_day3/link_list_test.py
True
0
False
3
213
2

Process finished with exit code 0

3.链表与顺序表的对比

操作 链表 顺序表
访问 O(n) O(1)
头插法 O(1) O(n)
尾插法 O(n) O(1)
指定位置插入法 O(n) O(n)
存储 可以存储在分散的存储空间中;需要存放下一元素的地址,导致占用内存较大 只能存放在连续的存储空间中;无需存放下一元素的地址

4.单向循环链表的实现

#!/usr/bin/env python
#! _*_ coding:UTF-8 _*_

class Node(object):
    '''链表的节点'''
    def __init__(self, elem):
        '''构造方法'''
        self.elem = elem
        self.next = None

class SingleCycleLinkList(object):
    '''单向循环链表'''
    def __init__(self, node=None):
        '''构造方法'''
        self.__head = node
        if node != None:
            node.next = node

    def is_empty(self):
        '''判断单向循环链表是否为空'''
        return self.__head == None

    def length(self):
        '''返回单向循环链表的长度'''
        if self.is_empty():
            return 0

        cur = self.__head
        count = 1
        while cur.next != self.__head:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        '''遍历单向循环链表'''
        if self.is_empty():
            return

        cur = self.__head
        str = ''
        while cur.next != self.__head:
            str += '%s ' % cur.elem
            cur = cur.next
        str += '%s' % cur.elem
        return str

    def add(self, item):
        '''单向循环链表头部插入元素'''
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = node
        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next

            node.next = self.__head
            self.__head = node
            cur.next = node

        return True

    def append(self, item):
        '''向单向循环链表尾部插入元素'''
        node = Node(item)
        if self.is_empty():
            self.__head = node
            node.next = node
        else:
            cur = self.__head
            while cur.next != self.__head:
                cur = cur.next
            node.next = self.__head
            cur.next = node

        return True

    def insert(self, pos, item):
        '''向单向链表指定位置插入元素'''
        if pos <= 0:
            self.add(item)
        elif pos > self.length() -1:
            self.append(item)
        else:
            pre = self.__head
            count = 0
            while pos - 1 > count:
                count += 1
                pre = pre.next
            node.next = pre.next
            pre.next = node
        return True

    def remove(self, item):
        '''删除单向循环链表中元素'''
        if self.is_empty():
            return True
        cur = self.__head
        pre = None
        while cur.next != self.__head:
            if cur.elem == item:
                if cur == self.__head:
                    rear = self.__head
                    while rear.next != self.__head:
                        rear = rear.next
                    self.__head = cur.next
                    rear.next = self.__head
                else:
                    pre.next = cur.next
                break

            else:
                pre = cur
                cur = cur.next

        if cur.item == item:
            if cur == self.__head:
                self.__head = None
            else:
                pre.next = cur.next
        return True

4.双向链表的实现

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 == None

    def length(self):
        """返回链表的长度"""
        cur = self._head
        count = 0
        while cur != None:
            count += 1
            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):
        """头部插入元素"""
        node = Node(item)
        if self.is_empty():
            # 如果是空链表,将_head指向node
            self._head = node
        else:
            # 将node的next指向_head的头节点
            node.next = self._head
            # 将_head的头节点的prev指向node
            self._head.prev = node
            # 将_head 指向node
            self._head = node

    def append(self, item):
        """尾部插入元素"""
        node = Node(item)
        if self.is_empty():
            # 如果是空链表,将_head指向node
            self._head = node
        else:
            # 移动到链表尾部
            cur = self._head
            while cur.next != None:
                cur = cur.next
            # 将尾节点cur的next指向node
            cur.next = node
            # 将node的prev指向cur
            node.prev = cur

    def search(self, item):
        """查找元素是否存在"""
        cur = self._head
        while cur != None:
            if cur.item == item:
                return True
            cur = cur.next
        return False

def insert(self, pos, item):
        """在指定位置添加节点"""
        if pos <= 0:
            self.add(item)
        elif pos > (self.length()-1):
            self.append(item)
        else:
            node = Node(item)
            cur = self._head
            count = 0
            # 移动到指定位置的前一个位置
            while count < (pos-1):
                count += 1
                cur = cur.next
            # 将node的prev指向cur
            node.prev = cur
            # 将node的next指向cur的下一个节点
            node.next = cur.next
            # 将cur的下一个节点的prev指向node
            cur.next.prev = node
            # 将cur的next指向node
            cur.next = node

def remove(self, item):
        """删除元素"""
        if self.is_empty():
            return
        else:
            cur = self._head
            if cur.item == item:
                # 如果首节点的元素即是要删除的元素
                if cur.next == None:
                    # 如果链表只有这一个节点
                    self._head = None
                else:
                    # 将第二个节点的prev设置为None
                    cur.next.prev = None
                    # 将_head指向第二个节点
                    self._head = cur.next
                return
            while cur != None:
                if cur.item == item:
                    # 将cur的前一个节点的next指向cur的后一个节点
                    cur.prev.next = cur.next
                    # 将cur的后一个节点的prev指向cur的前一个节点
                    cur.next.prev = cur.prev
                    break
                cur = cur.next

if __name__ == "__main__":
    ll = DLinkList()
    ll.add(1)
    ll.add(2)
    ll.append(3)
    ll.insert(2, 4)
    ll.insert(4, 5)
    ll.insert(0, 6)
    print "length:",ll.length()
    ll.travel()
    print ll.search(3)
    print ll.search(4)
    ll.remove(1)
    print "length:",ll.length()
    ll.travel()

注意:

is_empty() 链表是否为空

length() 链表长度

travel() 遍历链表

add(item) 链表头部添加

append(item) 链表尾部添加

insert(pos, item) 指定位置添加

remove(item) 删除节点

search(item) 查找节点是否存在

python数据结构与算法第七天【链表】的更多相关文章

  1. Java数据结构和算法(七)——链表

    前面博客我们在讲解数组中,知道数组作为数据存储结构有一定的缺陷.在无序数组中,搜索性能差,在有序数组中,插入效率又很低,而且这两种数组的删除效率都很低,并且数组在创建后,其大小是固定了,设置的过大会造 ...

  2. python数据结构与算法

    最近忙着准备各种笔试的东西,主要看什么数据结构啊,算法啦,balahbalah啊,以前一直就没看过这些,就挑了本简单的<啊哈算法>入门,不过里面的数据结构和算法都是用C语言写的,而自己对p ...

  3. Java数据结构和算法(七)B+ 树

    Java数据结构和算法(七)B+ 树 数据结构与算法目录(https://www.cnblogs.com/binarylei/p/10115867.html) 我们都知道二叉查找树的查找的时间复杂度是 ...

  4. Python数据结构与算法--List和Dictionaries

    Lists 当实现 list 的数据结构的时候Python 的设计者有很多的选择. 每一个选择都有可能影响着 list 操作执行的快慢. 当然他们也试图优化一些不常见的操作. 但是当权衡的时候,它们还 ...

  5. Python数据结构与算法--算法分析

    在计算机科学中,算法分析(Analysis of algorithm)是分析执行一个给定算法需要消耗的计算资源数量(例如计算时间,存储器使用等)的过程.算法的效率或复杂度在理论上表示为一个函数.其定义 ...

  6. Python数据结构与算法之图的最短路径(Dijkstra算法)完整实例

    本文实例讲述了Python数据结构与算法之图的最短路径(Dijkstra算法).分享给大家供大家参考,具体如下: # coding:utf-8 # Dijkstra算法--通过边实现松弛 # 指定一个 ...

  7. Python数据结构与算法之图的广度优先与深度优先搜索算法示例

    本文实例讲述了Python数据结构与算法之图的广度优先与深度优先搜索算法.分享给大家供大家参考,具体如下: 根据维基百科的伪代码实现: 广度优先BFS: 使用队列,集合 标记初始结点已被发现,放入队列 ...

  8. python数据结构与算法——链表

    具体的数据结构可以参考下面的这两篇博客: python 数据结构之单链表的实现: http://www.cnblogs.com/yupeng/p/3413763.html python 数据结构之双向 ...

  9. Python 数据结构和算法

    阅读目录 什么是算法 算法效率衡量 算法分析 常见时间复杂度 Python内置类型性能分析 数据结构 顺序表 链表 栈 队列 双端队列 排序与搜索 冒泡排序 选择排序 插入排序 希尔排序 快速排序 归 ...

随机推荐

  1. VS2015P配置opencv340

    1添加系统环境变量 F:\dongdong\0tool\navidia_cuda_opencv\opencv\build\x64\vc14\bin 注销重启 2 工程配置 选择好工程  x64 包含目 ...

  2. JS(1) JavaScript 用法

    HTML 中的脚本必须位于 <script> 与 </script> 标签之间. 脚本可被放置在 HTML 页面的 <body> 和 <head> 部分 ...

  3. python textwrap的使用

    参考:https://docs.python.org/3.6/library/textwrap.html textwrap模块提供了一些方便的函数,以及TextWrapper类,它执行所有的工作.如果 ...

  4. Generative Adversarial Nets[Vanilla]

    引言中已经较为详细的介绍了GAN的理论基础和模型本身的原理.这里主要是研读Goodfellow的第一篇GAN论文. 0. 对抗网络 如引言中所述,对抗网络其实就是一个零和游戏中的2人最小最大游戏,主要 ...

  5. Python-Django下载与基本命令

    1.下载Django: pip3 install django 2.创建一个django project django-admin.py startproject mysite 当前目录下会生成mys ...

  6. E. Superhero Battle

    链接 [https://codeforces.com/contest/1141/problem/E] 题意 怪物开始的生命值,然后第i分钟生命值的变化 问什么时候怪物生命值为非正 分析 有一个巨大的坑 ...

  7. Echarts x轴文本内容太长的几种解决方案

    Echarts 标签中文本内容太长的时候怎么办 ? - 1对文本进行倾斜 在xAxis.axisLabe中修改rotate的值 xAxis: { data: ["衬衫11111", ...

  8. 软工网络15团队作业7——Alpha冲刺之事后诸葛亮

    Deadline: 2018-5-16 22:00PM,以博客提交至班级博客时间为准 事后诸葛亮分析 Alpha冲刺,很多同学经历了"Learning by doing"的学一门新 ...

  9. py使用笔记-pandas函数

    1,nan替换为0df = df(np.nan, 0, regex=True)2.inf替换为0df= df(np.inf, 0.0, regex=True)3.从数据库读取数据到dataframei ...

  10. Azure系列2.1.10 —— CloudBlobClient

    (小弟自学Azure,文中有不正确之处,请路过各位大神指正.) 网上azure的资料较少,尤其是API,全是英文的,中文资料更是少之又少.这次由于公司项目需要使用Azure,所以对Azure的一些学习 ...