java linkedlist实现队列_JAVA专题七:用LinkedList实现栈与队列

用LinkedList实现一个栈

"栈"有进也被称为"后进先出"的容器。同其他Java容器一样,压进去与弹出来的东西都是Object,所以除非你只用Object的功能,否则就必须对弹出来的东西进行类型转换。

LinkedList的方法能直接实现栈的功能,所以你完全可以不写stack而直接使用LinkedList。

Making a stack from a LinkedList

A stack is sometimes referred to as a “last-in, first-out”

(LIFO) container. That is, whatever you “push” on the stack last

is the first item you can “pop” out. Like all of the other

containers in Java, what you push and pop are Objects, so you must

cast what you pop, unless you’re just using Object behavior.

Comment

The LinkedList has methods that directly implement stack

functionality, so you can also just use a LinkedList rather than

making a stack class. However, a stack class can sometimes tell the

story better:

package com.tao.zhu;

import java.util.*;

class Weekdays {

static final

String[] weekdays = {"Mon", "Tue", "Wed", "Thu", "Fri",

"Sat",

"Sun"};

}

public class StackL {

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

static void main(String[] args) {

StackL stack = new StackL();

for (int i = 0; i < 7; i++) {

stack.push(Weekdays.weekdays[i]);

}

System.out.println(stack.top());

System.out.println(stack.top());

System.out.println(stack.pop());

System.out.println(stack.pop());

System.out.println(stack.pop());

}

} ///:~

Output:

Sun

Sun

Sun

Sat

用LinkedList实现一个队列

队列是一个“先进先出”容器。你放东西的顺序也取东西的顺序。LinkedList有支持队列功能的方法,所以它也能当作队列来使用。

Making a queue from a LinkedList

A queue is a “first-in, first-out” (FIFO) container. That

is, you put things in at one end, and pull them out at the other.

So the order in which you put them in will be the same order that

they come out. LinkedList has methods to support queue behavior, so

these can be used in a Queue class:

Fripackage com.tao.zhu;

import java.util.LinkedList;

public class QueueL {

private

static LinkedList list = new LinkedList();

public void

put(Object v) {

list.addFirst(v);

}

public

Object get(){

return

list.removeLast();

}

public

boolean isEmpty(){

return

list.isEmpty();

}

public

static void main(String[] args) { QueueL queuel = new QueueL();

//for(int i=0; i

// queuel.put(Weekdays.weekdays[i]);

for(int i=0; i<5; i++)

queuel.put(Integer.toString(i));

while(!queuel.isEmpty())

System.out.println(queuel.get());

}

}

Output:

0

1

2

3

4

---The end

你可能感兴趣的:(java,linkedlist实现队列)