用栈实现十进制转换为x进制

参考:https://www.cnblogs.com/lixiaolun/p/4645247.html

1、链栈的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package linkStack;

public class {

Node base;
Node top;

public void init() {
base=new Node();
top=new Node();

base.data=null;
base.next=null;

top.data=null;
top.next=base;
}


public void push(Object e) {
Node node=new Node();
node.data=e;

//第一次入栈
if(top.next==base) {
node.next=base;
top.next=node;
}else {
node.next=top.next;
top.next=node;
}
}

//出栈
public void pop() {
if(top.next==base)
{
System.out.println("栈中没有元素!");
}else
{
System.out.println(top.next.data);
top.next=top.next.next;
}
}

public boolean isEmpty() {
if(top.next==base) {
return true;
}

return false;
}

public void printNode() {
Node temp=top;
while(temp.next!=base) {
temp=temp.next;
System.out.println(temp.data);
}
}

class Node{
Object data;
Node next;
}
}

2、进制转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package linkStack;

public class DToX {
//十进制转X进制
public static void main(String[] args) {
// TODO Auto-generated method stub

LinkStack stack=new LinkStack();
stack.init();

int d=16;//十进制数100
int x=2;//转为二进制

while(d!=0) {
stack.push(d%x);
d=d/x;
}

while(!stack.isEmpty())
{
stack.pop();
}
}

}