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
  • 相关阅读:
    安装VC6.0遇到的问题
    开发、测试环境
    OPENGL绘制文字
    C++实现文件关联
    MFC多国语言——配置文件
    MFC 资源记录
    如何解决——汉化英文界面出现乱码
    项目配置——添加第三方资源
    队列&生产者消费者模型
    抢票小程序
  • 原文地址:https://www.cnblogs.com/huahongzhenghexiu/p/12632047.html
Copyright © 2011-2022 走看看