单向循环链表

单向循环链表

class Node:
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None


class CycleLink:
    def __init__(self):
        self.head = None

    def is_empty(self):
        return self.head == None

    def length(self):
        if self.head == None:
            return 0
        cur = self.head
        count = 1
        while cur.next != self.head:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        if self.head == None:
            return 0
        cur = self.head
        while cur.next != self.head:
            print(cur.item)
            cur = cur.next

    def add(self, item):
        node = Node(item)
        if self.is_empty():
            self.head = node
            node.next = self.head
        else:
            node.next=self.head
            cur=self.head
            while cur.next!=self.head:
                cur=cur.next
            cur.next=node
            self.head=node



link = CycleLink()
print(link.length())
link.add(123)
print(link.length())
print('----------')
link.add(125)
link.add(126)
link.travel()

单向循环链表特点是最后一个节点并不是指向None,而是指向的是head指针。

单向循环链表的判断是否为空与单链表一样。求长度和遍历与单链表的条件判断不一样,判断的是是否为head指针。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值