实现基于链表的栈
代码实现:
import java.util.NoSuchElementException;
public class MyStack<E> {
private Node<E> head;//头结点
private Node<E> top;//栈顶
private int size;//栈中元素个数
public MyStack() {
head = new Node<E>();
head.next = null;
top = null;//栈顶初始化为null
size = 0;
}
/**
* 把item压入栈中
*
* @param item
*/
public void push(E item) {
/********** Begin *********/
if (top == null){
top = new Node<>();
}
Node temp = head;
while (temp.next != null){
temp = temp.next;
}
Node newNode = new Node();
newNode.item = item;
temp.next = newNode;
top = newNode;
size++;
/********** End *********/
}
/**
* 返回它栈顶元素并删除
*/
public E pop() {
if (isEmpty())
throw new NoSuchElementException("栈为空!");
/********** Begin *********/
Node temp = head.next;
while (temp.next != null){
if (temp.next.next == null){
break;
}
temp = temp.next;
}
Node topNode = top;
temp.next = null;
top = temp;
size--;
return (E) topNode.item;
/********** End *********/
}
/**
* 返回栈中元素个数
*
* @return
*/
public int size() {
return size;
}
/**
* 判断一个栈是否为空
*
* @return
*/
public boolean isEmpty() {
return (null == head);
}
//链表结点内部类
private static class Node<E> {
private E item;
private Node<E> next;
}
}
代码测试:
public class MyStackTest {
public static void main(String[] args) {
MyStack<String> s = new MyStack<>();
Scanner in = new Scanner(System.in);
while (in.hasNext()){
String str = in.next();
if (!str.equals("-")) {
s.push(str);
} else {
System.out.print(s.pop() + " ");
}
}
}
}
结果展示: