python 循环单向链表

单向循环链表python实现

python 循环单向链表_第1张图片
循环链表

结点

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

你可能感兴趣的:(python 循环单向链表)