栈的介绍,使用场景及数组实现,请看这篇文章。
栈的介绍,使用场景及数组实现
package cn.chmcyz.linkedstack;
/**
* @author 谌涣谋
* @date 2020/5/17 - 0:08
*/
public class LinkedStackDemo {
public static void main(String[] args) {
LinkedStack stack=new LinkedStack();
stack.push(new Node(1));
stack.push(new Node(2));
stack.push(new Node(3));
stack.push(new Node(4));
stack.push(new Node(5));
stack.show();
System.out.println(stack.pop()+"出栈");
System.out.println("======================");
stack.show();
System.out.println("栈顶的值为"+stack.peek());
System.out.println("======================");
stack.show();
}
}
class LinkedStack{
Node top=new Node(-1);
//遍历栈
public void show(){
Node temp=top;
while (temp.next!=null){
System.out.println(temp);
temp=temp.next;
}
System.out.println("================================");
}
//压栈
public void push(Node node){
node.next=top;
top=node;
}
//出栈
public Node pop(){
Node temp=top;
top=top.next;
return temp;
}
//取栈顶元素
public Node peek(){
return top;
}
}
class Node{
int number;
Node next;
public Node(int number) {
this.number = number;
}
@Override
public String toString() {
return "Node{" +
"number=" + number +
'}';
}
}