基础操作需要创建链表来存储数据
使用尾插法和尾删法来表示栈中的入栈和出栈
typedef struct node
{
int data;
struct node* next;
}Node,*LPNode;
LPNode creatnode(int data)
{
LPNode newnode = (LPNode)malloc(sizeof(Node));
assert(newnode);
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void insertbytail(LPNode &head,int data)
//这里要么传引用要么传二级指针因为这里head赋值并没有对主函数里面的head改变
{
if (head == NULL)
{
head = creatnode(data);
}
else
{
LPNode newnode = creatnode(data);
LPNode pmove = head;
while (pmove->next!=NULL)
{
pmove = pmove->next;
}
pmove->next = newnode;
}
}
void deletetail(LPNode head)
{
LPNode pronode = head;
if (head == NULL)
{
return;
}
LPNode posnode = head->next;
if (pronode->next == NULL)
{
cout << pronode->data;
free(pronode);
return;
}
while (posnode->next!= NULL)
{
pronode = posnode;
posnode = posnode->next;
}
cout << posnode->data ;
free(posnode);
pronode->next = NULL;
}
创建栈结构
typedef struct stack
{
int top;//用来判断是否为空
LPNode head;
}Stack,*LPStack;
//描述一个栈的最初始的状态
LPStack creatstack()
{
LPStack stack = (LPStack)malloc(sizeof(Stack));
assert(stack);
stack->top = 0;
stack->head = NULL;
return stack;
}
出栈入栈就是表现为链式结构的表尾插入和删除
void push(LPStack stack,int data)
{
insertbytail(stack->head, data);
stack->top++;
}
void pop(LPStack stack)
{
deletetail(stack->head);
stack->top--;
}
判断栈是否为空即判断 top==0
bool empty(LPStack stack)
{
return stack->top == 0;
}
代码实现
int main()
{
LPNode head = NULL;
LPStack stack = creatstack();
int n;
int num;
cin >> num;//表示数
cin >> n;//表示进制
while (num)
{
push(stack,num%n );
num /= n;
}
while (!empty(stack))
{
pop(stack);
}
return 0;
}
以上就是c/c++链式堆栈描述进制转换问题示例解析的详细内容,更多关于c/c++链式堆栈描述进制转换的资料请关注编程网其它相关文章!