链栈实现数制转换算法
时间: 2024-03-28 07:32:09 浏览: 24
链栈可以用来实现数制转换算法。下面是一个使用链栈实现通用数制转换程序的示例代码:
```python
class StackNode:
def __init__(self, data):
self.data = data
self.next = None
class LinkedStack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
new_node = StackNode(data)
new_node.next = self.top
self.top = new_node
def pop(self):
if self.is_empty():
return None
data = self.top.data
self.top = self.top.next
return data
def convert_decimal_to_base(decimal, base):
stack = LinkedStack()
digits = "0123456789ABCDEF"
is_negative = False
if decimal < 0:
is_negative = True
decimal = abs(decimal)
while decimal > 0:
remainder = decimal % base
stack.push(remainder)
decimal = decimal // base
result = ""
if is_negative:
result += "-"
while not stack.is_empty():
digit = stack.pop()
result += digits[digit]
return result
```
使用上述代码,你可以调用`convert_decimal_to_base`函数将任意一个十进制数转换成p进制的数。其中,`decimal`是待转化的十进制数,`base`是要转化的进制数。
例如,将十进制数15转换为二进制数和十六进制数,可以使用以下代码:
```python
decimal = 15
binary = convert_decimal_to_base(decimal, 2)
hexadecimal = convert_decimal_to_base(decimal, 16)
print("Binary: ", binary) # 输出:1111
print("Hexadecimal: ", hexadecimal) # 输出:F
```