链式存储结构,试着完成1-9九个数字的进栈和出栈的操作。
方法比较无脑,懒得想了
import java.util.EmptyStackException;
public class LinkedStackTest {
public static void main(String[] args) throws Exception {
LinkedStack stack = new LinkedStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
stack.push(9);
System.out.println("检测peek()方法 应该是最后压入栈中的9");
System.out.println("---->"+stack.peek());
System.out.println();
System.out.println("===下面是最初状态===");
System.out.println(stack);
System.out.println();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println("===弹出5个元素===");
System.out.println(stack);
System.out.println();
stack.pop();
stack.pop();
stack.pop();
System.out.println("===弹出3个元素,剩下一个元素是最初压入栈中的1===");
System.out.println(stack);
}
}
class LinkedStack<E>{
private class Node {
public E e;
public Node next;
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(E e, Node next) {
this.e = e;
this.next = next;
}
public Node(E e) {
this(e, null);
}
public Node() {
this(null, null);
}
@Override
public String toString() {
return e.toString();
}
}
private int size;
private Node dummyHead;
private Node top;
public LinkedStack() {
dummyHead = new Node(null,null);
size = 0;
top = dummyHead;
}
public boolean isEmpty() {
return this.size == 0;
}
public void push(E e){
Node node = new Node(e,null);
top.next = node;
top = top.next;
size++;
}
public Object peek() throws Exception {
if(isEmpty())
new EmptyStackException();
Object temp = top.getE();
return temp;
}
public Object pop() throws Exception {
if(isEmpty())
new EmptyStackException();
Object temp = top.getE();
Node last = dummyHead.next;
for (int i = 0 ; i < size-2 ; i++){
last = last.next;
}
top = last;
top.next = null;
size--;
return temp;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Node temp = dummyHead.next;
while (temp != null){
if (temp.next == null){
sb.append(temp.getE());
}
else {
sb.append(temp.getE());
sb.append("|");
}
temp = temp.next;
}
sb.append("]");
return sb.toString();
}
}