1、栈Stack
先进后出,LIFO
在Java中,我们用链表来实现栈和堆。
原因:
- 可存储任何类型数据。
- 不受数组空间定长的限制。
- 所需的空间总是和集合的大小成正比。
- 操作所需的时间和集合的大小无关。
栈的Java实现
public class Stack<T> {
//定义头节点
private Node first;
//定义存储容量
private int N;
//定义节点,存储数据和指向下一个元素的指针
class Node{
T item;
Node next;
}
public Stack() {
}
//压栈
public void push(T item){
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
//出栈
public T pop(){
T item = first.item;
first = first.next;
N--;
return item;
}
//大小
public int size(){
return N;
}
//是否空
public boolean isEmpty(){
return N ==0;
}
}
2、队列Queue
先进后出,排队顺序
public class Queue<T> {
//定义头节点 尾节点
private Node first;
private Node last;
private int size;
class Node {
T item;
Node next;
}
public Queue() {
first.next = last;
}
public void enqueue(T item) {
last.next = new Node();
if (isEmpty()) {
first = last;
}
else
last = last.next;
last.item = item;
size++;
}
public T dequeue() {
T item = first.item;
first = first.next;
if (isEmpty())
last = null;
size--;
return item;
}
public boolean isEmpty() {
return size == 0;
}
}