public class StackDemo {
public static void main(String[] args) {
//链表模拟栈测试
LinkedListStack stack = new LinkedListStack(3);
try {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
} catch (Exception e) {
System.out.println(e.getMessage());
}
stack.show();
try {
System.out.println("出栈:" + stack.pop());
System.out.println("出栈:" + stack.pop());
System.out.println("出栈:" + stack.pop());
System.out.println("出栈:" + stack.pop());
} catch (Exception e) {
System.out.println(e.getMessage());
}
stack.show();
}
}
class LinkedListStack {
private int maxSize;
private Node top;
public LinkedListStack(int maxSize) {
this.maxSize = maxSize;
top = new Node(0);
top.next = null;
}
public boolean isEmpty() {
return top.next == null;
}
public boolean isFull() {
return size() == maxSize;
}
public int size() {
if (isEmpty()) {
return 0;
}
Node cur = top;
int count = 0;
while (cur.next != null) {
count++;
cur = cur.next;
}
return count;
}
/*
头插入法
*/
public void push(int value) {
if (isFull()) {
System.out.println("栈满~");
return;
}
Node newNode = new Node(value);
//如果栈中还没有元素
if (isEmpty()) {
top.next = newNode;
return;
}
//如果栈中已经至少有一个元素,则把新添加的元素添加到链表头部
newNode.next = top.next;
top.next = newNode;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空~");
}
//获取该出栈元素的值
int out = top.next.num;
//把出栈的元素删除
top.next = top.next.next;
return out;
}
public void show() {
if (isEmpty()) {
System.out.println("栈空~");
return;
}
Node cur = top.next;
int i = 0;
while (cur != null) {
System.out.printf("arrar[%d]=%d\n", size()-i, cur.num);
i++;
cur = cur.next;
}
}
}
class Node {
public int num;
public Node next;
public Node(int num) {
this.num = num;
}
@Override
public String toString() {
return "Node{" +
"num=" + num +
'}';
}
}
单链表实现栈
最新推荐文章于 2022-05-08 12:57:55 发布