实现队列效果(先进先出)
public class Queue<T> {
LinkedList<T> linkedList;
public Queue(){
linkedList = new LinkedList<>();
}
public void put(T t){
linkedList.addFirst(t);
}
public T get(){
return linkedList.removeLast();
}
public boolean isEmpty(){
return linkedList.isEmpty();
}
测试:
Queue<Integer> queue = new Queue();
for(int i = 1; i < 6 ; i++ )
queue.put(i);
while (!queue.isEmpty())
System.out.print(queue.get() + "\t");
实现堆栈效果(先进后出)
public class StackL<T> {
LinkedList<T> linkedList;
public StackL(){
linkedList = new LinkedList<>();
}
public void push(T t){
linkedList.addFirst(t);
}
public T pop(){
return linkedList.removeFirst();
}
public boolean isEmpty(){
return linkedList.isEmpty();
}
}
测试:
StackL<Integer> stackL = new StackL();
for(int i = 1; i < 6 ; i++ )
stackL.push(i);
while (!stackL.isEmpty())
System.out.print(stackL.pop() + "\t");