完成下列程序,该程序实现栈的链式存储结构,构建链栈(栈中的元素依次为China,Japan,France,India,Australia),依次进行进栈和出栈操作,判断栈空和栈满操作,返回栈顶元素操作。要求生成链栈时,从键盘上读取数据元素。
时间: 2024-03-16 17:48:04 浏览: 72
以下是实现栈的链式存储结构的示例代码:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedStack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
new_node = Node(data)
new_node.next = self.top
self.top = new_node
def pop(self):
if self.is_empty():
return "Stack is empty"
else:
pop_node = self.top
self.top = pop_node.next
pop_node.next = None
return pop_node.data
def peek(self):
if self.is_empty():
return "Stack is empty"
else:
return self.top.data
stack = LinkedStack()
print(stack.is_empty()) # True
stack.push("China")
stack.push("Japan")
stack.push("France")
stack.push("India")
stack.push("Australia")
print(stack.peek()) # Australia
print(stack.pop()) # Australia
print(stack.pop()) # India
print(stack.pop()) # France
print(stack.pop()) # Japan
print(stack.pop()) # China
print(stack.is_empty()) # True
```
阅读全文