单向循环链表python实现

###单向循环链表python实现
循环链表
结点

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

###循环链表实现

#      单向循环链表
class SingleCycleLinkList(object):
    def __init__(self):
        self._head = None
    def is_empty(self):
        return  self._head == None
    def length(self):
        if self.is_empty():
            return  0
        count = 1
        cur = self._head
        while cur.next != self._head:
            cur = cur.next
            count += 1
        return  count
    # 遍历
    def travel(self):
        if self.is_empty():
            return
        current = self._head
        strs = 'item : ' + str(current.item)
        while  (current.next != self._head):
            current = current.next
            strs = strs + ', item : ' + str(current.item)
        print(strs)

###头节点添加

    #  头节点添加元素
    def add(self,item):
        node  = Node(item)
        if self.is_empty():
            self._head = node
            node.next = self._head
        else:
            node.next = self._head
            current = self._head
            while current.next != self._head:
                current = current.next
            current.next = node
            self._head = node

尾节点添加

    # 在尾部添加
    def append(self,item):
        node = Node(item)
        if self.is_empty():
            self.add(item)
        current = self._head
        while current.next != self._head:
            current = current.next
        current.next = node
        node.next = self._head

插入

    def insert(self,index ,item):
        node = Node(item)
        if index < 1:
            self.add(item)
        elif index > self.length() - 1:
            self.append(item)
        else:
            present = self._head
            count = 0
            while count < index - 1:
                present = present.next
                count += 1
            node.next = present.next
            present.next = node

删除

    # 删除item
    def remove(self,item):
        if self.is_empty():
            return
        current = self._head
        while current.next != self._head:
            preNode = current
            current = current.next
            if item != current.item:
                break
            else:
                preNode.next = current.next

###查找

    # 查找
    def search(self,item):
        if self.is_empty():
            return
        current = self._head
        node = None

        while current.next != self._head:
            current = current.next
            if current.item == item:
                print( 'search :' + str(item))
                node = current
        return  node

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值