1. 顺序栈实现十进制转换二进制
#include<stdlib.h>
#define Max 100
//定义顺序栈结构
typedef struct{
int data[Max];
int top;
}SeqStack;
//建立空栈
SeqStack *initStack()
{
SeqStack *S=(SeqStack*)malloc(sizeof(SeqStack));
if(S==NULL)
return NULL;
S->top=-1;
return S;
}
//入栈
int push_stack(SeqStack *S,int x)
{
if(S->top+1==Max)
return 0;
S->top++;
S->data[S->top]=x;
return 1;
}
int pop_stack(SeqStack *S,int *x)
{
if(S->top==-1)
return 0;
*x=S->data[S->top];
S->top--;
return 1;
}
//出栈
#include<stdio.h>
int main()
{
int x,a;
printf("Enter x:");
scanf("%d",&x);
SeqStack *S=initStack();
while(x!=0)
{
push_stack(S,x%2);
x=x/2;
}
while(S->top!=-1)
{
pop_stack(S,&a);
printf("%d",a);
}
}
文章来源地址https://www.toymoban.com/news/detail-735501.html
2.链栈实现十进制转换二进制
#include<stdlib.h>
#define Max 100
//定义链栈结构
typedef struct node{
int data;
struct node *next;
}LinkStack;
//建立空栈
LinkStack *initLStack()
{
LinkStack *top=(LinkStack*)malloc(sizeof(LinkStack));
if(top)
top->next=NULL;
return top;
}
//入栈
int push_stack(LinkStack *top,int x)
{
LinkStack *node=(LinkStack*)malloc(sizeof(LinkStack));
if(node==NULL)
return 0;
node->data=x;
node->next=top->next;
top->next=node;
return 1;
}
int pop_stack(LinkStack *top,int *x)
{
LinkStack *u;
if(top->next==NULL)
return 0;
u=top->next;
*x=u->data;
top->next=u->next;
free(u);
return 1;
}
//出栈
#include<stdio.h>
int main()
{
int x,a;
printf("Enter x:");
scanf("%d",&x);
LinkStack *top=initLStack();
while(x!=0)
{
push_stack(top,x%2);
x=x/2;
}
while(top->next!=NULL)
{
pop_stack(top,&a);
printf("%d",a);
}
return 0;
}
文章来源:https://www.toymoban.com/news/detail-735501.html
到了这里,关于数据结构——利用栈来实现进制转换的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!