链表实现栈
/**
* 链表实现栈
* @author heweihao
* @date: 2021/3/25 13:09
*/
public class LinkedStack {
private int count;
private Node node;
private int maxSize;
public LinkedStack(int maxSize){
this.maxSize = maxSize;
node = new Node();
}
public void push(int num){
if(isFull()){
System.out.println("栈满了");
return;
}
Node lastNode = node;
while (lastNode.next != null){
lastNode = lastNode.next;
}
Node pushNode = new Node();
pushNode.value = num;
lastNode.next = pushNode;
pushNode.pre = lastNode;
count++;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈内没有数据");
}
Node popNode = this.node.next;
while (popNode.next != null){
popNode = popNode.next;
}
int value = popNode.value;
popNode.pre.next = null;
count--;
return value;
}
public void list(){
if(isEmpty()){
System.out.println("栈内没有数据");
}
for (int i = count; i > 0; i--) {
System.out.printf("stack[%d] = %d\n",i,pop());
}
}
/**
* 栈满
*/
public boolean isFull() {
return count == maxSize;
}
/**
* 栈空
*/
public boolean isEmpty() {
if (node.next == null){
return true;
}
return false;
}
/**
* 链表元素
*/
