利用栈将输入的十进制数及一些基本的栈操作

时间:2020-12-23 20:17:30
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

import javax.swing.JScrollPane;



class test {
public static void main(String[] args) throws NumberFormatException,

IOException{
Stack stk = new Stack();
System.out.print("请输入一个正整数:");
BufferedReader strin=new BufferedReader(new InputStreamReader

(System.in));
int temp=Integer.parseInt(strin.readLine());
do{
//用堆栈 10 % 2 把余数压入堆栈后 再弹出
stk.push(temp%2);
temp=temp/2;

}while(temp!=0);
while(!stk.empty()){
System.out.print(stk.pop()+" ");
}

}
}
/*一些对栈的基本操作
* #include <stdio.h>
#define StackSize 100
typedef int ElemType;
typedef struct{
ElemType data[StackSize];
int top;
}SqStack;
/*初始化
void InitStack(SqStack *s)
{
s->top=-1;
}
*/
/*压栈
int push(SqStack *s,ElemType e)
{
if(s->top<StackSize-1)
{
s->top=s->top+1;
s->data[s->top]=e;
return 1;
}
else
{
printf("overflow!/n");
return 0;
}
}
*/

/*出栈

ElemType pop(SqStack *s)
{
ElemType e;
if(-1==s->top)
{
printf("underflow/n");
return 1;
}
else
{
e=s->data[s->top];
(s->top)--;
return e;
}
}
*/