python实现顺序表
2024-09-01 05:14:28
python实现顺序表可以有两中形式进行存储
- 列表
- 元组
其实简单来说,顺序表无非就是操作列表和元组的方法来对顺序表进行操作。
实例代码
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
最新文章
- selenium的安装
- Java逐行读写TXT文件
- HBuilder从下载到使用
- Asp.Net Mvc Areas 的用法与好处
- Fatal error in launcher: Unable to create process using &#39;";&#39;
- C#获取程序集的版本号和最后编译时间
- 读书笔记-实用单元测试(英文版) Pragmatic Unit Testing in C# with NUnit
- 认识Backbone (二)
- Win10下CISCO VPN Client无法安装解决方案
- cocos2dx 图片压缩工具 推荐
- S2第一本书内测
- 【一天一道LeetCode】#69. Sqrt(x)
- ToolbarDemo【Toolbar作为顶部导航栏的简单使用】
- douyin-bot-代码
- keil软件错误总结.doc
- 第40章:MongoDB-集群--Replica Sets(副本集)---副本集的管理
- web全栈架构师[笔记] — 02 数据交互
- Runable和Thread
- Ubuntu 12.04硬盘安装教程
- 剑指offer四十五之扑克牌顺子(序列是否连续)