数据结构:单向循环链表(六)

单向循环链表的操作

remove(item)  删除元素

思路:1、当链表为空,直接返回即可

   2、设置两个指针,一个指向当前节点,另一个指向前一个节点;

   3、循环遍历,循环条件:cur.next  !=  self.__head

   4、进入循环,判断cur.item是否大于item

    这时候分情况考虑,如果第一个节点就是要删除的元素,这时候应该把头节点指向cur.next;而这里还需要做一个遍历:尾节点也应该指向cur.next;这时候新加一个指针cur1用于循环,循环条件同样为cur1 != self.__head ,当cur1指向尾节点时,让cur1.next=cur.next(这时候cur指向第一个节点) 同时self.__head=cur.next

   5、删除元素在中间的情况,我们只要让pre.next=cur.next就好了

   6、跳出循环后,我们再考虑当删除元素在链表尾部的情况,同样只需要将pre.next=cur.next即可(这里的特殊情况,当链表只有一个元素的时候,应该使self.__head=None)

class Node(object)    
"""节点"""    
  def __init__(self, item)        
    self.item = item        
    self.next = None
class SinCycLinkedlist(object):
    """单向循环链表"""
    def __init__(self,node=None):
        self.__head=node
        while node:
            node.next=self.__head


    def remove(item):
        if self.__head==None:
            return 
        cur=self.__head
        per=None
        while cur.next != self.__head :
            if cur.item == item:
                if cur==self.__head:
                    cur1=self._head
                    while cur1.next != self.__head:
              cur1=cur1.next
            self.__head=cur.next
            cur1.next=cur.next
            return
                else:
                    pre.next=cur.next
            return
            else:
                pre=cur
                cur=cur.next
        if cur.item == item:
       if cur.next==self._head:
          self._head=None
       else:
          pre.next=cur.next   

  

posted @ 2020-05-14 14:53  Roronoa-Zoro  阅读(124)  评论(0)    收藏  举报