• 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
  • 相关阅读:
    查看python关键字
    命令终端执行python
    Codeforces-462C. A Twisty Movement
    Codeforces-462A. A Compatible Pair
    Codeforces-446C. Pride
    Codeforces-Hello 2018C. Party Lemonade(贪心)
    Codeforces-33C. Wonderful Randomized Sum
    Codeforces-118D. Caesar's Legions(lazy dynamics)
    codeforces-73C. LionAge II
    Gym 101510C-Computer Science
  • 原文地址:https://www.cnblogs.com/huahongzhenghexiu/p/12632047.html
Copyright © 2020-2023  润新知