java实现栈的反转

来源:互联网 发布:nginx书籍 编辑:程序博客网 时间:2024/05/19 11:45
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);

}
}

}
}
原创粉丝点击