JAVA利用LinkedList构造栈与队列

import java.util.LinkedList;
import java.util.ListIterator;



public class Stack {

	private LinkedList list = new LinkedList();
	public void push(Object v){list.addFirst(v);}
	public Object top(){return list.getFirst();}
	public Object pop(){return list.removeFirst();}
	public boolean isEmpty(){return list.isEmpty();}
	
	public ListIterator listIterator(){
		return list.listIterator();
	}
	
	
	public static void main(String[] args) {
		Stack s = new Stack();
		s.push("b");
		s.push("a");
		s.push("c");
		s.push("d");
		System.out.println(s.top());
		s.pop();
		
		ListIterator iter = s.listIterator();
		while(iter.hasNext()){
			System.out.println(iter.next());
		}
	}
}

 上面利用LinkedList构造一个栈。后进先出。对链表来说即增加,删除均在一方,取栈顶也在这一方。

下面看构造队列。

队列先进先出,即添加与删除在不同的一方。

import java.util.LinkedList;
import java.util.ListIterator;


public class Queue {

	private LinkedList list = new LinkedList();
	public void push(Object v){list.addFirst(v);}
	public Object pop(){return list.removeLast();}
	public boolean isEmpty(){return list.isEmpty();}
	public ListIterator listIterator(){
		return list.listIterator();
	}
	
	public static void main(String[] args) {
		
		Queue q = new Queue();
		q.push("a");
		q.push("b");
		q.push("c");
		printQueue(q);
		q.pop();
		printQueue(q);
		
	}
	
	public static void printQueue(Queue q){
		ListIterator iter = q.listIterator();
		while(iter.hasNext()){
			System.out.println(iter.next());
		}
		System.out.println("finished");
	}
	
}

 输出结果为:

c
b
a
finished
c
b
finished
 

你可能感兴趣的:(java,C++,c,C#)