python-实现链式栈
2024-08-29 04:01:26
7 """
8 用一个类来实现一个节点
9 """
10 class Node(object):
11 def __init__(self,data):
12 self.data = data
13 self.next = None
14 class linkstack(object):
15 def __init__(self):
16 self.top = None
17 def isEmpty(self):
18 return self.top == None
19 def clear(self):
20 self.top = None
21 def length(self):
22 i = 0
23 tempnode =self.top
24 while tempnode is not None:
25 tempnode = tempnode.next
26 i += 1
27 return i
28 def push(self,item):
29 node = Node(item)
30 node.next = self.top
31 self.top = node
32 def pop(self):
33 self.top = self.top.next
34 def gettop(self):
35 return self.top.data
36 def display(self):
37 if self.top == None:
38 print("None")
39 tempnode = self.top
40 while tempnode is not None:
41 print(tempnode.data,end = " ")
42 tempnode = tempnode.next
43 print()
44
45 if __name__ == "__main__":
46 linkstack1 = linkstack()
47 linkstack1.push(1)
48 linkstack1.push(2)
49 linkstack1.push(3)
50 linkstack1.push(4)
51 linkstack1.push(5)
52 linkstack1.push(6)
53 linkstack1.display()
54 print(linkstack1.gettop())
55 print(linkstack1.length())
56 linkstack1.pop()
57 linkstack1.display()
58 linkstack1.clear()
59 linkstack1.display()
60 print(linkstack1.isEmpty())
运行结果
6 5 4 3 2 1
6
6
5 4 3 2 1
None
True
代码逻辑较为简单所以代码没有注释,如果有什么地方不明白,欢迎留言!
最新文章
- PHP运行环境,服务器相关配置
- 调用百度地图API
- 环境变量NLS_LANG
- nodeJS---express4+passport实现用户注册登录验证
- [题解+总结]NOIP2015模拟题2
- microstrip(微带线)、stripline(带状线) 指什么?
- dedecms5.7安装百度(ueditor)编辑器的方法
- SEDA工作笔记(一)
- Windows7下MySQL5.6.15免安装版的配置(来自yang362046076)
- Scrapy爬虫大战京东商城
- Java-NIO(五):通道(Channel)的数据传输与内存映射文件
- shell编程的笔记
- window apache 多站点配置
- oracle extract函数
- Oracle EBS 快捷键
- JS中的new操作符原理解析
- HOJ 1108
- [重磅]Deep Forest,非神经网络的深度模型,周志华老师最新之作,三十分钟理解!
- 51nod 1118 机器人走方格
- Linux文件属性,类型,ls -lhi解释行列