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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值