Java栈操作
直接上代码
Node类
public class Node {
Object info;//数据域
Node next;//节点
//有参构造
Node(Object info, Node next) {
this.info = info;
this.next = next;
}
//有参构造
Node(Object info) {
this(info, null);
}
}
Main方法
public class Main {
public static void main(String[] args) {
MyStack mq = new MyStack();
String s = "alibaba";
for (int i = s.length() - 1; i >= 0; i--) {
mq.push(s.charAt(i));//入栈
}
String rs = "";
while(!mq.isEmpty()) rs += mq.pop();
System.out.println(rs);
}
}
MyStack类
public class MyStack {
Node head;
//无参构造
public MyStack() {head = null;}
//判空
public boolean isEmpty() {return head == null;}
//入栈
public void push(Object info)
{Node p = new Node(info);
if(isEmpty()) head = p;
else {p.next = head; head = p;}
}
//出栈
public Object pop()
{if(isEmpty()) return null;
Object info = head.info;
head = head.next;
return info;
}
public Object top()
{if(isEmpty()) return null;
Object info = head.info;
return info;
}
//清空
public void clear() {head = null;}
}