一、node节点实现
class Node{
public Node pre;
public Node next;
public int val;
public Node(int val) {
this.val = val;
}
}
public class NodeStack {
private Node head;
private Node tail;
public boolean isEmpty() {
return head == null;
}
public void push(int value) {
Node node = new Node(value);
if (isEmpty()){
head = node;
tail = node;
return;
}
tail.next = node;
node.pre = tail;
tail = node;
}
public Integer pop() {
if (isEmpty()) return null;
if (tail.pre == null){
int result = tail.val;
head = null;
tail = null;
return result;
}
Node node = tail;
tail.pre.next = null;
node.pre = null;
return node.val;
}
public Integer peek() {
if (isEmpty()) return null;
return tail.val;
}
public void list() {
Node current = head;
while (current.next != null){
System.out.printf(current.val + " ");
current = current.next;
}
System.out.println(current.val);
}
}
二、链表实现
public class ListStack {
private List<Integer> list;
private int maxSize;
public ListStack(int maxSize) {
this.list = new LinkedList<>();
this.maxSize = maxSize;
}
public boolean isFull() {
return list.size() == maxSize;
}
public boolean isEmpty() {
return list.size() == 0;
}
public void push(int value) {
if (isFull()) return;
list.add(value);
}
public Integer pop() {
if (isEmpty()) return null;
Integer result = list.get(list.size() - 1);
list.remove(list.size() - 1);
return result;
}
public void list() {
System.out.println(list);
}
}
三、数组实现
public class XinStack {
int top = -1;
int[] intlist;
int maxSize;
public XinStack(int maxSize) {
this.maxSize = maxSize;
intlist = new int[maxSize];
}
public boolean isFull(){
return top == maxSize - 1;
}
public void push(int value){
if (!isFull()){
top++;
intlist[top] = value;
}else {
System.out.println("stack is full");
}
}
public int pop(){
if (top > -1){
int value = intlist[top];
top--;
return value;
}else {
throw new RuntimeException("元素已经没有了");
}
}
public void list(){
if (maxSize < 0){
return;
}
for (int i = top; i >= 0 ; i--) {
System.out.printf(intlist[i] + " ");
}
System.out.print("\n");
}
}