用不同的存储方法,实现栈的基本操作
时间: 2023-05-21 12:03:48 浏览: 70
可以使用数组或链表来实现栈的基本操作,以下是使用数组实现栈的基本操作的示例代码:
```python
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise Exception("Stack is empty")
return self.items.pop()
def peek(self):
if self.is_empty():
raise Exception("Stack is empty")
return self.items[-1]
def size(self):
return len(self.items)
```
使用链表实现栈的基本操作的示例代码如下:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, item):
new_node = Node(item)
new_node.next = self.top
self.top = new_node
def pop(self):
if self.is_empty():
raise Exception("Stack is empty")
item = self.top.data
self.top = self.top.next
return item
def peek(self):
if self.is_empty():
raise Exception("Stack is empty")
return self.top.data
def size(self):
count = 0
current = self.top
while current is not None:
count += 1
current = current.next
return count
```
以上是两种常见的栈的实现方式,可以根据具体需求选择合适的实现方式。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)