python双链表(代码)

class Node(object):
    def __init__(self, item):
        self.item = item
        # 下一个节点
        self.next = None
        # 上一个节点
        self.pre = None


class DoubleLinkList(object):
    def __init__(self):
        self.__head = None

    def is_empty(self):
        """链表是否为空"""
        return self.__head is None

    def length(self):
        """链表长度"""
        count = 0
        cur = self.__head
        while cur is not None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        """遍历链表"""
        cur = self.__head
        while cur is not None:
            print(cur.item,end=' ')
            cur = cur.next

    def add(self, item):
        """链表头部添加"""
        node = Node(item)
        if self.is_empty():
            self.__head = node
            return
        node.next = self.__head
        self.__head.pre = node
        self.__head = node

    def append(self, item):
        """链表尾部添加"""

        if self.is_empty():
            self.add(item)
        else:
            node = Node(item)
            cur = self.__head
            while cur.next is not None:
                cur = cur.next
            node.pre = cur
            cur.next = node

    def insert(self, pos, item):
        """指定位置添加"""
        if pos <= 0:
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            node = Node(item)
            index = 0
            cur = self.__head
            while index < (pos - 1):
                cur = cur.next
                index += 1
            # 当前位置就是插入的前节点
            node.next = cur.next
            node.pre = cur
            cur.next.pre = node
            cur.next = node

    def remove(self, item):
        """删除节点"""
        cur = self.__head
        while cur is not None:
            if cur.item == item:
                # 删除的是尾节点
                if cur.next is None:
                    cur.pre.next = None
                # 删除的是首节点
                elif cur.pre is None:
                    self.__head = cur.next
                else:
                    cur.pre.next = cur.next
                    cur.next.pre = cur.pre
                return
            cur = cur.next

    def search(self, item):
        """查找节点是否存在"""
        cur = self.__head
        while cur is not None:
            if cur.item == item:
                return True
            cur = cur.next
        return False

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值