• python实现单链表


    class Node:
        def __init__(self, data):
            self.data = data
            self.next = None
    
    
    class LinkedList:
        def __init__(self, node=None):
            self.__head = node
    
        def is_empty(self):
            """链表是否为空"""
            return self.__head == None
    
        def length(self):
            """链表长度"""
            cur = self.__head
            count = 0
            while cur != None:
                count += 1
                cur = cur.next
            return count
    
        def travel(self):
            """遍历链表"""
            cur = self.__head
            while cur != None:
                print(cur.data)
                cur = cur.next
            return
    
        def add(self, item):
            """链表头部新增节点"""
            node = Node(item)
            node.next = self.__head
            self.__head = node
    
        def push(self, item):
            """链表尾部push节点"""
            node = Node(item)
            cur = self.__head
            if not cur:
                self.__head = node
                return
            while cur.next != None:
                cur = cur.next
            cur.next = node
    
        def insert(self, pos, item):
            """链表中间插入节点"""
            if pos <= 0:
                self.add(item)
            elif pos > self.length() - 1:
                self.push(item)
            else:
                node = Node(item)
                cur = self.__head
                count = 0
                while count < pos - 1:
                    count += 1
                    cur = cur.next
                node.next = cur.next
                cur.next = node
    
        def remove(self, item):
            """链表删除指定元素"""
            cur = self.__head
            if cur.data == item:
                self.__head = cur.next
                return
            while cur.next.data != item:
                cur = cur.next
            cur.next = cur.next.next
    
        def search(self, pos):
            """链表查找指定序号元素"""
            cur = self.__head
            if not pos:
                return cur
            count = 0
            while count != pos:
                count += 1
                cur = cur.next
            return cur
  • 相关阅读:
    表单序列化
    创建.ignore文件
    头条数学救火队长马丁的一道中山大学研究生入学考试数学分析题
    实数理论
    方法
    目标
    闭区间有限覆盖定理
    零值定理的确界原理证明方法,来自百度
    各种范例
    零值定理
  • 原文地址:https://www.cnblogs.com/huahongzhenghexiu/p/12632047.html
Copyright © 2020-2023  润新知