用链表生成一个栈
其他
2018-05-08 23:00:00
阅读次数: 0
package 栈;
/** * 定义一个结点 * @author Administrator * */ class Node{
Node next= null;
int data;
public Node(int data){
this.data = data;
}
} /** * 用链表创建一个栈 * @author Administrator * */ public class Stack {
Node top = null;
/**
* 判断链表是否为空
* @return
*/
public boolean isEmpty(){
return top == null;
}
/**
* 向栈中添加元素
*/
public void push(int data){
Node node = new Node(data);
node.next = top;
top = node;
}
/**
* 从栈中取元素
*/
public int pop(){
if(this.isEmpty()){
return (Integer) null;
}
int data = top.data;
top = top.next;
return data;
}
/**
* 取栈的峰值
* @return
*/
public int peek(){
if(this.isEmpty()){
return (Integer) null;
}
return top.data;
}
/**
* 返回栈中的元素个数
* @return
*/
public int size(){
int size = 0;
Node tmp = top;
while(tmp!=null){
size++;
tmp = tmp.next;
}
return size;
}
/**
* 打印栈
*/
public void printStack(){
Node tmp = top;
while(tmp != null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(2);
stack.push(1);
stack.push(4);
stack.push(5);
stack.push(3);
System.out.println("打印栈:");
stack.printStack();
System.out.println("栈的大小:");
System.out.println(stack.size());;
System.out.println("取出一个元素:");
System.out.println(stack.pop());
}
} |
转载自blog.csdn.net/lz1170063911/article/details/80095252