zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Java:day11
    Java:day10
    Java:day9
    Java:day8
    纯虚函数和抽象类
    C++的虚拟继承
    派生类构造函数、析构函数的定义和调用次序
    c++的继承方式——公有、保护、私有
    操作系统中系统调用的执行过程
    C++的类
  • 原文地址:https://www.cnblogs.com/huahongzhenghexiu/p/12632047.html
Copyright © 2011-2022 走看看