java實現棧的反轉

class Node {
char data;
Node next;

public Node(char data) {
this.data = data;
next = null;
}
}


class LinkStack {
Node first;

public LinkStack() {

first = null;
}

public boolean isEmpty() {

return first == null;
}

public boolean push(Node node) {

node.next = first;
first = node;

return true;
}

public Node pop() {
if (isEmpty()) 
return null;

Node tmp;
tmp = first;
first = first.next;

return tmp;
}
}
public class ReverseStack {
public static void main(String[] args) {
LinkStack stackIn = new LinkStack();
LinkStack stackOut = new LinkStack();

String str = "hello world!";
char[] a = str.toCharArray();

Node node = new Node(' ');
stackIn.push(node);

for (char x : a) {
Node n = new Node(x);
stackIn.push(n);
}

while (stackIn.first != null) {
stackOut.push(stackIn.pop());

if (stackOut.first.data == ' ') {
while (stackOut.first != null)
System.out.print(stackOut.pop().data);

}
}

}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章