python实现·数据结构与算法之双向循环链表

双向循环链表定义

双向循环链表(Double Cycle Linked List)是双向链表的一种更复杂的变形,头结点的上一节点链接域指向尾结点,而尾结点的下一节点链接域指向头节点。

节点示意图

python实现·数据结构与算法之双向循环链表_第1张图片

  • 表元素域elem用来存放具体的数据。
  • 链接域prev用来存放上一个节点的位置(python中的标识)
  • 链接域next用来存放下一个节点的位置(python中的标识)

双向循环链表示意图

python实现·数据结构与算法之双向循环链表_第2张图片

双向循环链表的基本操作

  • is_empty() 判断链表是否为空
  • length 链表长度
  • travel() 遍历整个链表,打印元素
  • add(item) 在链表头部添加元素
  • append(item) 在链表尾部添加元素
  • insert(pos, item) 在指定位置插入元素
  • remove(item) 删除元素
  • clear() 清空链表
  • is_contain(item) 判断元素是否存在

Python 代码实现

# 节点代码实现

class Node(object):
    """双向链表节点"""
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None
# 双向循环链表代码实现

class DoubleCycleLinkList(object):
    """双向循环链表"""
    def __init__(self):
        self._head = None

    def is_empty(self):
        """判断链表是否为空"""
        return self._head is None
    
    @property
    def length(self):
        """返回链表的长度"""
        if self.is_empty():
            return 0
        count = 1
        cur = self._head
        while cur.next != self._head:
            count += 1
            cur = cur.next
        return count
    
    def travel(self):
        """遍历链表"""
        if self.is_empty():
            return
        cur = self._head
        print(cur.item)
        while cur.next != self._head:
            cur = cur.next
            print(cur.item)
        print("")
        
    def add(self,item):
        """头部添加节点"""
        node = Node(item)
        if self.is_empty():
            # 如果是空链表,将_head指向node
            self._head = node
            # 将node的next指向_head的头节点
            node.next = self._head
            # node.prev = self._head
            self._head.prev = node
        else:
            # 尾结点为 self._head.prev
            # 尾结点next指向node
            self._head.prev.next = node
            # node的prev指向尾结点
            node.prev = self._head.prev
            # 将node的next指向头节点self._head
            node.next = self._head
            # 头结点的prev指向node
            self._head.prev = node
            # 头指针指向node
            self._head = node
    
    def append(self, item):
        """尾部添加元素"""
        node = Node(item)
        if self.is_empty():
            # 如果是空链表,将_head指向node
            self._head = node
        else:
            # 尾部节点为self._head.prev
            # 尾结点的next指向node
            self._head.prev.next = node
            # node的prev指向尾结点
            node.prev = self._head.prev
            
        # 将node的next指向头节点self._head
        node.next = self._head
        # 头指针指向node
        self._head.prev = node
    
    def is_contain(self, item):
        """查找节点是否存在"""
        if self.is_empty():
            return False
        cur = self._head
        if cur.item == item:
            return True
        while cur.next != self._head:
            cur = cur.next
            if cur.item == item:
                return True
        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.next = cur.next
            cur.next.prev = node
            node.prev = cur
            cur.next = node
            
    def remove(self, item):
        """删除一个节点"""
        # 若链表为空,则直接返回
        if self.is_empty():
            return
        # 将cur指向头节点
        cur = self._head
        # 若头节点的元素就是要查找的元素item
        if cur.item == item:
            # 如果链表不止一个节点
            if cur.next != self._head:
                # 尾节点为self._head.prev
                # 尾节点的next指向self._head.next
                self._head.prev.next = self._head.next
                # self._head.next为新头节点,其prev指向尾结点
                self._head.next.prev = self._head.prev
                # 头指针指向新节点
                self._head = self._head.next
            else:
                # 链表只有一个节点
                self._head = None
        else:
            pre = self._head
            # 第一个节点不是要删除的
            while cur.next != self._head:
                # 找到了要删除的元素
                if cur.item == item:
                    # 删除
                    cur.prev.next = cur.next
                    cur.next.prev = cur.prev
                    return
                else: 
                    cur = cur.next
            # cur 指向尾节点
            if cur.item == item:
                # 尾部删除
                self._head.prev = cur.prev
                cur.prev.next =  self._head
    
    def clear(self):
        """清空链表"""
        self._head = None
                
    def __len__(self):
        """可使用len()获取链表长度"""
        return self.length
    
    def __iter__(self):
        """可使用循环遍历链表"""
        if self.is_empty():
            return
        cur = self._head
        yield cur.item
        while cur.next != self._head:
            cur = cur.next
            yield cur.item
    
    def __contains__(self, item):
        """可使用in判断元素是否在链表中"""
        return self.is_contain(item)
# 测试数据

if __name__ == '__main__':
    print("---创建链表---")
    dcl_list = DoubleCycleLinkList()
    dcl_list.add(1)
    dcl_list.add(2)
    dcl_list.append(3)
    dcl_list.insert(2, 4)
    dcl_list.insert(4, 5)
    dcl_list.insert(0, 6)
    print("length:",len(dcl_list))
    dcl_list.travel()
    print(dcl_list.is_contain(3))
    print(dcl_list.is_contain(8))
    print(3 in dcl_list)
    print(8 in dcl_list)
    print("---中间删除元素 1---")
    dcl_list.remove(1)
    print("length:",len(dcl_list))
    dcl_list.travel()
    print("---头部删除元素 6---")
    dcl_list.remove(6)
    print("length:",len(dcl_list))
    dcl_list.travel()
    print("---尾部删除元素 5---")
    dcl_list.remove(5)
    print("length:",len(dcl_list))
    dcl_list.travel()
    print("---循环遍历---")
    for i in dcl_list:
        print(i)
# 输出结果

---创建链表---
length: 6
6
2
1
4
3
5

True
False
True
False
---中间删除元素 1---
length: 5
6
2
4
3
5

---头部删除元素 6---
length: 4
2
4
3
5

---尾部删除元素 5---
length: 3
2
4
3

---循环遍历---
2
4
3

算法分析

操作 复杂度
访问元素 O ( n ) O(n) O(n)
在头部插入/删除 O ( 1 ) O(1) O(1)
在尾部插入/删除 O ( 1 ) O(1) O(1)
在中间插入/删除 O ( n ) O(n) O(n)

联系我们

个人博客网站:http://www.bling2.cn/

Github地址:https://github.com/lb971216008/Use-Python-to-Achieve

知乎专栏:https://zhuanlan.zhihu.com/Use-Python-to-Achieve

小专栏:https://xiaozhuanlan.com/Use-Python-to-Achieve

博客园:https://www.cnblogs.com/Use-Python-to-Achieve

关注微信公众号【不灵兔】,获取更多资料

你可能感兴趣的:(Python实现,python,数据结构,算法,链表)