1、实现顺序栈的基本操作:构造空栈、入栈、出栈、取栈顶元素。 2、输入一包含’[‘ ‘]’ “(”和“)”的字符串,检测括号是否匹配(其中括号中能嵌套括号),并输出括号是否匹配的信息。 输入一个十进制数, 输出其对应的八进制数
时间: 2024-05-08 07:16:02 浏览: 29
1. 顺序栈的基本操作实现:
```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]
```
2. 括号匹配检测实现:
```python
def check_brackets(string):
stack = Stack()
for char in string:
if char in ['[', '(']:
stack.push(char)
elif char in [']', ')']:
if stack.is_empty():
return False
top = stack.peek()
if (char == ']' and top == '[') or (char == ')' and top == '('):
stack.pop()
else:
return False
return stack.is_empty()
```
3. 十进制转八进制实现:
```python
def decimal_to_octal(decimal):
stack = Stack()
while decimal > 0:
remainder = decimal % 8
stack.push(remainder)
decimal //= 8
octal = ''
while not stack.is_empty():
octal += str(stack.pop())
return octal
```
阅读全文