7、广义表的应用 要求实现的广义表的建立、查找、输出、取表头和取表尾以及求深度等。 设计用一个主控菜单程序控制(1)建立广义表 (2)输出广义表 (3)结点的查找 (4)求广义表表头 (5)求广义表表尾 (6)求广义表的深度
时间: 2024-05-04 19:22:28 浏览: 152
以下是广义表的实现示例,包括建立、查找、输出、取表头和取表尾以及求深度等功能。主控菜单程序控制如下:
```python
class GLNode:
def __init__(self, tag, value=None, sublist=None):
self.tag = tag
self.value = value
self.sublist = sublist
def create_glist(string):
stack = []
top = None
for c in string:
if c == '(':
stack.append(top)
top = None
elif c == ')':
if stack:
parent = stack.pop()
if parent.sublist:
parent.sublist.append(top)
else:
parent.value = top
top = parent
elif c == ',':
if top:
if top.sublist:
top.sublist.append(GLNode('atom', ''))
else:
top.sublist = [GLNode('atom', '')]
else:
top = GLNode('atom', '')
else:
if top:
top.tag = 'list'
top.sublist = [GLNode('atom', c)]
else:
top = GLNode('atom', c)
return top
def print_glist(node):
if not node:
return
if node.tag == 'atom':
print(node.value, end='')
else:
print('(', end='')
print_glist(node.value)
p = node.sublist
while p:
print(',', end='')
print_glist(p.value)
p = p.sublist
print(')', end='')
def search_glist(node, target):
if not node:
return False
if node.tag == 'atom':
return node.value == target
else:
if search_glist(node.value, target):
return True
p = node.sublist
while p:
if search_glist(p.value, target):
return True
p = p.sublist
return False
def get_head(node):
if not node:
return None
if node.tag == 'atom':
return node
else:
return node.value
def get_tail(node):
if not node:
return None
if node.tag == 'atom':
return None
else:
return node.sublist
def get_depth(node):
if not node:
return 0
if node.tag == 'atom':
return 1
else:
max_depth = 1
p = node.sublist
while p:
max_depth = max(max_depth, get_depth(p.value) + 1)
p = p.sublist
return max_depth
while True:
print('1. 建立广义表')
print('2. 输出广义表')
print('3. 查找结点')
print('4. 求广义表表头')
print('5. 求广义表表尾')
print('6. 求广义表的深度')
print('7. 退出程序')
choice = int(input('请选择操作:'))
if choice == 1:
string = input('请输入广义表字符串:')
glist = create_glist(string)
elif choice == 2:
print_glist(glist)
print()
elif choice == 3:
target = input('请输入要查找的结点:')
if search_glist(glist, target):
print('找到了!')
else:
print('没有找到。')
elif choice == 4:
head = get_head(glist)
if head:
print_glist(head)
print()
else:
print('表头不存在。')
elif choice == 5:
tail = get_tail(glist)
if tail:
print_glist(tail)
print()
else:
print('表尾不存在。')
elif choice == 6:
depth = get_depth(glist)
print('广义表的深度为', depth)
elif choice == 7:
break
else:
print('输入有误,请重新输入。')
```
以上代码中,`GLNode` 类表示广义表的结点,包含 `tag`(标记为 'list' 或 'atom')、`value`(原子结点的值)和 `sublist`(子表结点的列表)。`create_glist` 函数根据输入的字符串建立广义表并返回根结点。`print_glist` 函数输出广义表的字符串表示。`search_glist` 函数查找广义表中是否存在指定的结点。`get_head` 和 `get_tail` 函数分别返回广义表的表头和表尾。`get_depth` 函数返回广义表的深度。
主控菜单程序控制用户进行不同的操作,例如建立广义表、输出广义表、查找结点、求广义表表头、求广义表表尾和求广义表的深度等。用户输入数字选择要执行的操作。如果输入有误,则程序提示用户重新输入。
阅读全文
相关推荐
















