python 实现链表,单链表、双链表

python 实现链表,单链表、双链表

内容

#  _*_ coding:utf-8 _*_
"""单链表、双链表、单向循环列表"""


class Node(object):
    """节点"""
    def __init__(self, item):
        # _item 存放数据元素
        self.item = item
        # _next 是下一个节点的标识,后继节点
        self.next = None
        # 前驱节点
        self.prev = None


class SingleLinkList(object):
    """单链表"""
    def __init__(self, node=None):
        self._head = node

    @property
    def is_empty(self) -> bool:
        """链表是否为空"""
        return self._head is None

    @property
    def length(self) -> int:
        """链表长度"""
        cur = self._head        # cur 游标,用来移动遍历节点
        count = 0       # 记录数量
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    @property
    def travel(self) -> list:
        """遍历整个链表"""
        cur = self._head
        _items = []
        while cur is not None:
            _items.append(cur.item)
            cur = cur.next
        return _items

    def add(self, item) -> Node:
        """链表头部添加元素,头插法"""
        node = Node(item)
        node.next, self._head = self._head, node
        return node

    def append(self, item) -> Node:
        """链表尾部添加元素,尾插法"""
        node = Node(item)
        if self.is_empty:
            self._head = node
        else:
            cur = self._head
            while cur.next is not None:
                cur = cur.next
            cur.next = node
        return node

    def insert(self, pos, item) -> Node:
        """
        指定位置添加元素
        :param pos: 从 0 开始
        :param item: 节点值
        :return:
        """
        if pos <= 0:
            node = self.add(item)
        elif pos > self.length - 1:
            node = self.append(item)
        else:
            cur = self._head
            count = 0
            while count < pos - 1:
                count += 1
                cur = cur.next
            node = Node(item)
            node.next, cur.next = cur.next, node
        return node

    def remove(self, pos: int = None, item=None) -> Node:
        """
        删除节点
        :param pos: 需要删除节点的索引,从 0 开始
        :param item: 根据节点元素删除
        :return:
        """
        node = cur = self._head
        pre = None
        if pos is not None:
            count = 0
            while cur is not None:
                if count == pos:
                    node = cur
                    if cur == self._head:
                        self._head = cur.next
                    else:
                        pre.next = cur.next
                    break
                else:
                    pre, cur = cur, cur.next
                count += 1
        else:
            while cur is not None:
                if cur.item == item:
                    node = cur
                    if cur == self._head:
                        self._head = cur.next
                    else:
                        pre.next = cur.next
                    break
                else:
                    pre, cur = cur, cur.next
        return node

    def search(self, pos: int = None, item=None) -> Node:
        """
        查找节点是否存在,存在则返回节点的索引列表,否则返回空列表
        :param pos: 根据索引查找节点,返回节点对象
        :param item: 根据元素查找节点,返回节点对象列表
        :return:
        """
        cur = self._head
        if pos is not None:
            count = 0
            while cur is not None:
                if pos == count:
                    return cur
                cur = cur.next
                count += 1
        else:
            while cur is not None:
                if cur.item == item:
                    return cur
                cur = cur.next


class DoubleLinkList(SingleLinkList):
    """双链表"""
    def __init__(self, node=None):
        super().__init__(node=node)

    def add(self, item) -> Node:
        """链表头部添加元素,头插法"""
        node = Node(item)
        node.next, self._head, node.next.prev = self._head, node, node
        return node

    def append(self, item) -> Node:
        """链表尾部添加元素,尾插法"""
        node = Node(item)
        if self.is_empty:
            self._head = node
        else:
            cur = self._head
            while cur.next is not None:
                cur = cur.next
            cur.next, node.prev = node, cur
        return node

    def insert(self, pos, item) -> Node:
        """
        指定位置添加元素
        :param pos: 从 0 开始
        :param item: 节点值
        :return:
        """
        if pos <= 0:
            node = self.add(item)
        elif pos > self.length - 1:
            node = self.append(item)
        else:
            cur = self._head
            count = 0
            while count < pos:
                count += 1
                cur = cur.next
            node = Node(item)
            node.next, node.prev, cur.prev.next, cur.prev = cur, cur.prev, node, node
        return node

    def remove(self, pos: int = None, item=None) -> Node:
        """
        删除节点
        :param pos: 需要删除节点的索引,从 0 开始
        :param item: 根据节点元素删除
        :return:
        """
        node = cur = self._head
        if pos is not None:
            count = 0
            while cur is not None:
                if count == pos:
                    node = cur
                    if cur == self._head:
                        self._head = cur.next
                        if cur.next:  # 判断链表是否只有一个节点
                            cur.next.prev = None
                    else:
                        cur.prev.next = cur.next
                        if cur.next:
                            cur.next.prev = cur.prev
                    break
                else:
                    cur = cur.next
                count += 1
        else:
            while cur is not None:
                if cur.item == item:
                    node = cur
                    if cur == self._head:
                        self._head = cur.next
                        if cur.next:    # 判断链表是否只有一个节点
                            cur.next.prev = None
                    else:
                        cur.prev.next = cur.next
                        if cur.next:
                            cur.next.prev = cur.prev
                    break
                else:
                    cur = cur.next
        return node


if __name__ == '__main__':
    # ll = SingleLinkList()
    ll = DoubleLinkList()
    print(ll.is_empty)      # True
    print(ll.travel)        # []
    ll.append(1)            # [1]
    print(ll.is_empty)      # False
    print(ll.travel)

    ll.append(2)            # [1, 2]
    print(ll.travel)
    ll.add(8)               # [8, 1, 2]
    print(ll.travel)
    ll.append(3)            # [8, 1, 2, 3]
    print(ll.travel)
    ll.append(4)            # [8, 1, 2, 3, 4]
    print(ll.travel)
    ll.append(5)            # [8, 1, 2, 3, 4, 5]
    print(ll.travel)
    ll.append(6)            # [8, 1, 2, 3, 4, 5, 6]
    print(ll.travel)
    ll.insert(-1, 9)        # [9, 8, 1, 2, 3, 4, 5, 6]
    print(ll.travel)
    ll.insert(2, 100)       # [9, 8, 100, 1, 2, 3, 4, 5, 6]
    print(ll.travel)
    ll.insert(10, 200)      # [9, 8, 100, 1, 2, 3, 4, 5, 6, 200]
    print(ll.travel)
    print(ll.length)
    ll.remove(0)            # [8, 100, 1, 2, 3, 4, 5, 6, 200]
    print(ll.travel)
    ll.remove(2)            # [8, 100, 2, 3, 4, 5, 6, 200]
    print(ll.travel)
    ll.remove(ll.length-1)  # [8, 100, 2, 3, 4, 5, 6]
    print(ll.travel)
    ll.remove(item=8)       # [100, 2, 3, 4, 5, 6]
    print(ll.travel)
    ll.remove(item=3)       # [100, 2, 4, 5, 6]
    print(ll.travel)
    ll.remove(item=6)       # [100, 2, 4, 5]
    print(ll.travel)
    print(ll.length)



单链表测试

在这里插入图片描述

双链表测试运行截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值