CodeGym /Java 博客 /China /数据结构：堆栈和队列

Vasyl Malik
Senior Java Developer at CodeGym

数据结构：堆栈和队列

Java 中的堆栈

public class Card {

public Card(String name) {
this.name = name;
}

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Card{" +
"name='" + name + '\'' +
'}';
}
}

import java.util.Stack;

public class SimpleCardGame {

// Draw deck
private Stack<Card> deck;

public Card getCardFromDeck() {
return deck.pop();
}

}

public Card lookAtTopCard() {

return deck.peek();
}

// ...getters, setters, etc.
}

• 从一副牌中取出一张牌（getCardFromDeck()方法）
• 查看顶部的卡（lookAtTopCard() 方法）。让我们假设这是一个“智力”奖励，它允许玩家找出游戏中的下一张牌。

• push() — 将项目添加到堆栈的顶部。当我们把一张牌打入弃牌堆时，它就在该弃牌的顶部
• pop() — 从堆栈中移除顶部元素并返回该元素。这个方法非常适合实现玩家抽牌的动作。
• peek() — 返回堆栈的顶部元素，但不将其从堆栈中移除

import java.util.Stack;

public class Main3 {

public static void main(String[] args) {

// Create a deck and add cards to it
Stack<Card> deck = new Stack<>();
deck.push(new Card("Ragnaros"));
deck.push(new Card("Patches the Pirate"));
deck.push(new Card("Sylvanas Windrunner"));
deck.push(new Card("Millhouse Manastorm"));
deck.push (new Card ("Edwin VanCleef"));

// Start the game
SimpleCardGame game = new SimpleCardGame();
game.setDeck(deck);

// The first player draws 3 cards from the deck
Card card1 = game.getCardFromDeck();
Card card2 = game.getCardFromDeck();
Card card3 = game.getCardFromDeck();

System.out.println("Which cards went to the first player?");
System.out.println(card1);
System.out.println(card2);
System.out.println(card3);

// The first player discards 3 of his cards

System.out.println("What cards are in the discard pile?");
}
}

Card{name='Edwin VanCleef"}
Card{name='Millhouse Manastorm'}
Card{name='Sylvanas Windrunner'}

Card{name='Sylvanas Windrunner'}
Card{name='Millhouse Manastorm'}
Card{name='Edwin VanCleef"}

Java 中的队列

All known subinterfaces

BlockingDeque<E>, BlockingQueue<E>, Deque<E>, TransferQueue<E>

All known implementing classes

AbstractQueue, ArrayBlockingQueue, ArrayDeque

PriorityBlockingQueue, PriorityQueue, SynchronousQueue

All implemented interfaces:

Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>

• peekFirst() — 返回第一个元素（但不将其从队列中删除）。
• peekLast() — 返回最后一个元素（但不将其从队列中删除）。
• pollFirst() — 返回队列中的第一个元素并将其删除。
• pollLast() — 返回队列中的最后一个项目并将其删除。