• python实现顺序表


    python实现顺序表可以有两中形式进行存储

    1. 列表
    2. 元组

    其实简单来说,顺序表无非就是操作列表和元组的方法来对顺序表进行操作。

    实例代码

     7 class SqList: 
      8     def __init__(self,maxsize = 10):
      9         self.curlen = 5#顺序表的初始化长度
     10         self.maxsize = maxsize#顺序表的最大长度
     11         self.listitem = [1,2,3,4,5]#顺序表存储空间
     12     def clear(self):
     13         """将顺序表置为空表"""
     14         self.curlen = 0
     15     def empty(self):
     16         """判断顺序表是否为空"""
     17         return delf.curlen == 0
     18     def length(self):
     19         return self.curlen
     20     def get(self,i):
     21         if i < 0 or i > self.curlen - 1:
     22             raise Exception("第i个元素不存在")                     
     23         return self.listitem[i]
     24     def insert1(self,i,x):
     25         """插入的x作为第i个元素"""
     26         if i < 0 or i > self.curlen - 1:
     27             raise Exception("插入位置非法")
     28         if self.curlen == self.maxsize:
     29             raise Exception("列表已满")
     30         """   
     31         for j in range(self.curlen,i - 1,-1):
     32             self.listitem[j] = self.listitem[j - 1]
    32             self.listitem[j] = self.listitem[j - 1]
     33         """   
     34         self.listitem.insert(i,x)
     35         self.curlen += 1
     36     def remove(self,i):
     37         if i < 0 or i > self.curlen - 1:
     38             raise Exception("删除位置非法")
     39         """   
     40         for j  in range(i,self.curlen):
     41             self.listitem[j] = self.listitem[j + 1]
     42         """   
     43         del self.listitem[i]
     44         self.curlen -= 1
     45     def index(self,x):
     46         for i in range(self.curlen):
     47             if self.listitem[i] == x:
     48                 return i
     49         return -1
     50     def display(self):
     51         for i in range(self.curlen):
     52             print(self.listitem[i],end = "")
     53         print()
     54               
     55 list1 = SqList()
     56 print(list1.listitem[0])
     57 print(list1.get(1))
     58 list1.insert1(1,9)
     59 list1.display()
     60 list1.remove(1)
     61 list1.display()                  

    运行结果

    1
    2
    192345
    12345

    笨鸟先飞
  • 相关阅读:
    C# 编码解码
    asp.net跨域问题
    C# crc16modbus
    c# 日志生成
    C# 对newtonsoft.json对象进行ascii排序
    C# 字节转结构体、结构体转字节
    按ascill排序参数
    C# Rsa加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)
    Interview
    Leetcode
  • 原文地址:https://www.cnblogs.com/zoutingrong/p/13903174.html
Copyright © 2020-2023  润新知