棧是先存進去的數(shù)據(jù)只能最后被取出來牍氛,是FILO(First In Last Out缨伊,先進后出)请毛。
用鏈表實現(xiàn)棧:
class Node<E>{
Node<E> next = null;
E data;
public Node(E data) {this.data = data;}
}
public class Stack<E>{
Node<E> top = null;
public boolean isEmpty(){
return top == null;
}
public void push(E data){
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop(){
if(this.isEmpty()){
return null;
}
E data = top.data;
top = top.next;
return data;
}
public E peek(){
if(isEmpty()) {
return null;
}
return top.data;
}
}
隊列是FIFO(First In First Out粘我,先進先出)臣缀,它保持進出順序一致坝橡。
class Node<E> {
Node<E> next =null;
E data;
public Node(E data){
this.data = data;
}
}
public class MyQueue<E> {
private Node<E> head = null;
private Node<E> tail = null;
public boolean isEmpty(){
return head = tail;
}
public void put(E data){
Node<E> newNode = new Node<E>(data);
if(head == null && tail == null){
head = tail = newNode;
}else{
tail.next = newNode;
taile = newNode;
}
}
public E pop(){
if(this.isEmpty()){
return null;
}
E data = head.data;
head = head.next;
return data;
}
public int size(){
Node<E> tmp = head;
int n = 0;
while(tmp != null) {
n++;
tmp = tmp.next;
}
return n;
}
public static void main(String []args){
MyQueue<Integer> q = new MyQueue<Integer>();
q.put(1);
q.put(2);
q.put(3);
System.out.println("隊列長度:" + q.size());
System.out.println("隊列首元素:" + q.pop());
System.out.println("隊列首元素:" + q.pop());
}
}
輸出結果:
隊列長度:3
隊列首元素:1
隊列首元素:2
注:
如果需要實現(xiàn)多線程安全,要對操作方法進行同步精置,用synchronized修飾方法