参考:栈和队列就是这么简单,Java栈实现,Java队列实现
java栈实现
public class LinkedListStack {
private LinkedList ll = new LinkedList();
public void push(int value) {
ll.insertFirst(value);
}
public int pop() throws Exception {
return ll.deleteFirst();
}
public void display() {
ll.display();
}
public void clearStack(){
ll.clear();
}
public static void main(String[] args) throws Exception {
LinkedListStack lls = new LinkedListStack();
lls.push(1);
lls.push(2);
lls.push(3);
lls.display();
System.out.println("出栈----:"+lls.pop());
lls.display();
System.out.println("清除----");
lls.clearStack();
System.out.println("入栈-----");
lls.push(4);
lls.display();
}
}
public class LinkedListStack {
private LinkedList ll = new LinkedList();
public void push(int value) {
ll.insertFirst(value);
}
public int pop() throws Exception {
return ll.deleteFirst();
}
public void display() {
ll.display();
}
public void clearStack(){
ll.clear();
}
public static void main(String[] args) throws Exception {
LinkedListStack lls = new LinkedListStack();
lls.push(1);
lls.push(2);
lls.push(3);
lls.display();
System.out.println("出栈----:"+lls.pop());
lls.display();
System.out.println("清除----");
lls.clearStack();
System.out.println("入栈-----");
lls.push(4);
lls.display();
}
}
java实现队列
public class FirstLastList {
private class Node{
private int value;
private Node next;
Node( int value){
this. value = value;
}
}
private Node first = null;
private Node last = null;
public void insertLast( int value){
Node Node = new Node( value);
if(first == null){
first = Node;
}else{
last.next = Node;
}
last = Node;
}
public int deleteFirst() throws Exception{
if(first == null)
throw new Exception("empty");
Node temp = first;
if(first.next == null)
last = null;
first = first.next;
return temp. value;
}
public void display(){
if(first == null)
System.out.println("empty");
System.out.print("first -> last : | ");
Node cur = first;
while(cur != null){
System.out.print(cur.value + " | ");
cur = cur.next;
}
System.out.print("\n");
}
public void clear(){
first = null;
last = null;
}
}
public class FirstLastListQueue {
private FirstLastList fll = new FirstLastList();
public void push(int value){
fll.insertLast(value);
}
public int pop() throws Exception{
return fll.deleteFirst();
}
public void display(){
fll.display();
}
public void clearQueue(){
fll.clear();
}
public static void main(String[] args) throws Exception{
FirstLastListQueue fllq = new FirstLastListQueue();
fllq.push(1);
fllq.push(2);
fllq.push(3);
fllq.display();
System.out.println("出队----"+fllq.pop());
fllq.display();
fllq.push(4);
fllq.display();
System.out.println("清除---");
fllq.clearQueue();
fllq.display();
fllq.push(5);
fllq.display();
}
}