链表:单链表及其操作

函数实现:

  • 单链表的初始化;
  • 单链表的判空;
  • 单链表的长度;
  • 单链表的插入节点:头插、尾插、随机插入;
  • 单链表的遍历节点;
  • 单链表的删除节点;
  • 单链表的查找节点(搜索节点);

代码:

class Node(object):
    """节点"""
    def __init__(self, elem):
        self.elem = elem
        self.next = None
        
class SingleLinkList(object):
    """单链表"""
    def __init__(self, node = None):
        self.__head = node
        
    def is_empty(self):
        """链表是否为空"""
        return self.__head == None
    
    def length(self):
        # 游标用来遍历节点
        cur = self.__head
        # 节点计数器,初始值影响while循环的判断条件
        counter = 0
        while cur != None :
            counter += 1
            cur = cur.next
        return counter
            
    def travel(self):
        cur = self.__head
        while cur != None:
            print(cur.elem)
            cur = cur.next
        
    def add(self, item):
        """链表头部添加元素"""
#         print("=====头插法=====")
        node = Node(item)
        node.next = self.__head
        self.__head = node
    
    def append(self, item):
        """链表尾部添加元素"""
        node = Node(item)
#         print("=====尾插法=====")
#         特殊情况
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node
    
    def insert(self, pos, item):
        """
        指定位置添加元素
        @pos: 从0开始 例:insert(2,100)        
        
        """
        if pos <= 0 :
            self.add(item)
        elif pos > (self.length() - 1):
            self.append(item)
        else:
            node = Node(item)
            pre = self.__head
            count = 0
            while count < (pos - 1):
                pre = pre.next
                count += 1
    #             当循环退出后,pre指向pos-1位置
            node.next = pre.next
            pre.next = node
        
    def search(self, item):
        """查找节点是否存在"""
        cur = self.__head
        while cur != None:
            if cur.elem == item:
                return True
            else:
                cur = cur.next
        return False
    
#     难度系数高
    def remove(self, item):
        cur = self.__head
        pre = None
        while cur != None:
            if cur.elem == item:
#                 判断此节点是否为头节点
                if cur == self.__head:
                    self.__head = cur.next
                else:
                    pre.next = cur.next
                break
#                 pass
            else:
                pre = cur
                cur = cur.next
                
                
                                
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章