Python 数据结构之双向链表的实现

双向链表:

  • 即每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。当节点既是头结点又是尾节点时,两个链接均为空值。
# 双向链表基于Python语言的实现
'''
双向链表需要实现的方法:
is_empty() 链表是否为空
len() 链表长度
travel() 遍历整个链表
add(item) 链表头部添加元素
append(item) 链表尾部添加元素
insert(pos, item) 指定位置添加元素
remove(item) 删除节点
search(item) 查找节点是否存在
'''

class Node(object):
    """
    节点类
    """
    def __init__(self, value):
        # 元素域
        self.value = value
        # 指向下节点 尾节点时为空
        self.next = None
        # 指向前节点 头节点时为空
        self.prev = None


class BothWayLinkList(object):
    """
    双向链表类
    """
    def __init__(self, node=None):
        # 初始化头节点
        self.__head = node

    def __len__(self):
        """
        返回链表长度
        """
        # 游标,用来遍历链表
        cur = self.__head
        # 记录遍历次数
        count = 0
        # 当前节点为None则说明已经遍历完毕
        while cur:
            count += 1
            cur = cur.next
        return count

    def is_empty(self):
        """
        判断链表是否为空
        """
        # 头节点不为None则不为空
        return self.__head == None

    def add(self, value):
        """
        头部插法
        先让新节点的next指向头节点
        再将头节点替换为新节点
        顺序不可错,要先保证原链表的链不断,否则头节点后面的链会丢失
        """
        node = Node(value)
        if self.is_empty():
            self.__head = node
        else:
            node.next = self.__head
            self.__head.prev = node
            self.__head = node

    def append(self, value):
        """
        尾部插法
        """
        node = Node(value)
        cur = self.__head
        if self.is_empty():
            self.__head = node
        else:
            while cur.next:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def insert(self, pos, value):
        """
        指定位置插入元素
        """
        # 应对特殊情况
        if pos <= 0:
            self.add(value)
        elif pos > len(self) - 1:
            self.append(value)
        else:
            node = Node(value)
            prior = self.__head
            count = 0
            # 在插入位置的前一个节点停下
            while count < (pos - 1):
                prior = prior.next
                count += 1
            # 先将插入节点与节点后的节点连接,防止链表断掉,先链接后面的,再链接前面的
            node.next = prior.next
            # 将下一个的prev指向新节点
            prior.next.prev = node
            # 将新节点的prev指向prior
            node.prev = prior
            # 将prior的next指向新节点
            prior.next = node

    def remove(self, value):
        """
        移除元素
        """
        cur = self.__head
        prior = None
        while cur:
            if value == cur.value:
                # 判断此节点是否是头节点
                if cur == self.__head:
                    self.__head = cur.next
                else:
                    prior.next = cur.next
                    cur.next.prev = prior
                break
            # 还没找到节点,继续遍历
            else:
                prior = cur
                cur = cur.next

    def search(self, value):
        """
        搜索元素
        """
        cur = self.__head
        while cur:
            if value == cur.value:
                return True
            cur = cur.next
        return False

    def travel(self):
        """
        遍历链表
        """
        cur = self.__head
        while cur:
            print(cur.value)
            cur = cur.next
    

if __name__ == "__main__":
    link_list = BothWayLinkList()
    link_list.append('a')
    link_list.append('b')
    link_list.append('d')
    # link_list.insert(2, 'c')
    link_list.travel()
    print(len(link_list))
    print(link_list.search(3))
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haeasringnar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值