将非负十进制整数转换成八进制数存入一链队列中后输出
时间: 2024-02-01 18:03:26 浏览: 83
好的,下面是将非负十进制整数转换成八进制数存入一链队列中后输出的示例代码:
```python
# 定义链式队列节点
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
# 定义链式队列
class Queue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def enqueue(self, data):
node = Node(data)
if self.tail is None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.is_empty():
return None
else:
node = self.head
self.head = node.next
if self.head is None:
self.tail = None
return node.data
# 将非负十进制整数转换成八进制数并存入队列中
def decimal_to_octal(decimal):
octal = ''
while decimal > 0:
octal = str(decimal % 8) + octal
decimal //= 8
return octal if octal else '0'
def convert_and_output(decimal):
q = Queue() # 存储八进制数
octal = decimal_to_octal(decimal)
for digit in octal:
q.enqueue(int(digit))
while not q.is_empty():
digit = q.dequeue()
print(digit, end=' ')
# 测试
convert_and_output(12345) # 输出: 3 0 0 7 1
```
希望能帮到您!
阅读全文