python实现一个无序单链表

摘要:
new_ Value):“”“初始化空链接列表”“self_ head=节点()self._ tail=非self._ length=0defisEmpty(self):
class Node:
    """先定一个node的类"""

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

    def getValue(self):
        return self.value

    def getNext(self):
        return self.next

    def setValue(self, new_value):
        self.value = new_value

    def setNext(self, new_next):
        self.next = new_next


class LinkedList:
    """实现一个单向链表及其各类操作方法"""

    def __init__(self):
        """初始化空链表"""
        self._head = Node()
        self._tail = None
        self._length = 0

    def isEmpty(self):
        """检测是否为空"""
        return self._head is None

    def add(self, value):
        """add在链表前端添加元素:O(1)"""
        newnode = Node(value)
        newnode.setNext(self._head)
        # 注意这里的顺序不能和setNext()颠倒不然新增的节点找不到next
        self._head = newnode

    def append(self, value):
        """append在链表尾部添加元素:O(n)
        思路:遍历链表,在原链尾next指向新节点"""
        newnode = Node(value)
        if self.isEmpty():
            # 若为空表,将添加的元素设为第一个元素
            self._head = newnode
        else:
            # 从链首遍历链表
            current = self._head
            while current.getNext() is not None:
                current = current.getNext()
            # 找到最后一个,直接设置它的next指向新增的节点
            current.setNext(newnode)

    def size(self):
        """获取链表的元素个数
        从链头head开始遍历到链尾,同时用变量累加经过的节点个数"""
        current = self._head
        while current is not None:
            current = current.getNext()
            self._length += 1
        return self._length

    def search(self, value):
        """查找元素是否在链表,找到返回True,否则返回False
        从链头head开始遍历到链尾,并判断当前节点的数据是否为目标value"""
        current = self._head
        found = False
        while current is not None and not found:
            if current.getValue() == value:
                found = True
            else:
                current = current.getNext()
        return found

    def remove(self, value):
        """删除一个元素
        遍历链表"""
        current = self._head
        previous = None
        found = False

        while not found:
            if current.getValue() == value:
                found = True
                # 找到后判断value是不是链首,是的话,head为value的下个节点
                if not previous:
                    self._head = current.getNext()
                else:
                    # 不是的话,将前一个节点的next指向要删除的节点的下一个节点
                    previous.setNext(current.getNext())
            elif current.getNext() is not None:
                # 之前的节点指向当前节点
                previous = current
                # 并找下一个节点作为循环的当前节点
                current = current.getNext()
            else:
                raise ValueError('{} is not in LinkedList'.format(value))

    def index(self, value):
        """返回元素在链表的位置,找不到抛出ValueError错误
        遍历链表,并用count累加遍历过的每一个节点位置"""
        current = self._head
        count = 0
        found = False

        while current is not None and not found:
            if current.getValue() == value:
                found = True
            else:
                current = current.getNext()
                count += 1
        if found:
            return count
        else:
            raise ValueError('{} is not in LinkedList'.format(value))

    def insert(self, position, value):
        """往链表position位置插入一个元素value"""
        # 如果是链首,直接add添加
        if position <= 1:
            self.add(value)
        # 如果是链尾,直接append
        elif position > self.size():
            self.append(value)
        # 中间位置插入,思路也是从头遍历,找到position位置之前一个节点插入
        # 并修改previous节点next指向新节点,新节点next指向position位置的节点
        else:
            temp = Node(value)
            previous = None
            count = 1
            current = self._head
            while count < position:
                count += 1
                previous = current
                current = current.getNext()

            previous.setNext(temp)
            temp.setNext(current)


if __name__ == '__main__':
    link = LinkedList()
    link.add(4)
    link.add(5)
    link.add(6)
    link.add(7)
    print(link.remove(4))
    print(link.size())

免责声明:文章转载自《python实现一个无序单链表》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇TS基础数据加工ETL下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

ElasticSearch安装拼音插件(pinyin)

环境介绍 集群环境如下: Ubuntu14.04 ElasticSearch 2.3.1(3节点) JDK1.8.0_60 开发环境: Windows10 JDK 1.8.0_66 Maven 3.3.3 Intellij IDEA 2016.1 下载编译Pinyin clone elasticsearch-analysis-pinyin 通过...

局部变量和全局变量的区别

局部变量和全局变量的区别局部变量可以与全局变量重名,但是局部变量会屏蔽全局变量。要使用全局变量,需要使用::。在函数体内引用变量会用到同名的局部变量而不是全局变量,对于一些编译器来说,在同一个函数体内可以定义多个同名的局部变量。例如我们可以在一个函数内部,在两个循环中都定义同名的局部变量i,而局部变量i的作用域在那个循环体内        具体来说,全局变...

k8s存储之emptyDir、hostPath和nfs存储卷

Volume  容器磁盘上的文件的生命周期是短暂的,这就使得在容器中运行重要应用时会出现一些问题。首先,当容器崩溃时,kubelet会重启它,但是容器中的文件将丢失——容器以干净点状态(镜像最初点状态)重新启动。其次,在pod中同时运行多个容器时,这些容器之间通常需要共享文件。Kubernetes中的volume就能很好的解决了这些问题。 1.背景 Doc...

redis跳表简介

转自:https://baijiahao.baidu.com/s?id=1625500811386005937&wfr=spider&for=pc 一、前言 跳表(Skip List)这种数据结构在一般的数据结构书籍和算法书籍里都不怎么涉及----至少我大学数据结构课程没有讲这种结构。但是跳表确实是一种性能比较优秀的动态数据结构,并且Red...

分布式一致性算法--Raft

     前面一篇文章讲了Paxos协议,这篇文章讲它的姊妹篇Raft协议,相对于Paxos协议,Raft协议更为简单,也更容易工程实现。有关Raft协议和工程实现可以参考这个链接https://raft.github.io/,里面包含了大量的论文,视屏已经动画演示,非常有助于理解协议。概念与术语leader:领导者,提供客户提供服务(生成写日志)的节点,...

使用Distinct()内置方法对List集合的去重 问题

说到对集合去重处理,第一时间想到的肯定是Linq的Distinct扩展方式,对于一般的值类型集合去重,很好处理,直接list.Distinct()即可。但是如果想要对一个引用类型的集合去重(属性值都相同就认为重复),就会发现,直接Distinct()是不行的 先来看看泛型链表 List<T> 的定义:public class List<T...