java实现stack和queue
1、stack
java语言实现stack。
package kb.algorithm;
public class Stack<Item> {
private Node first;
private int N;
public boolean empty() {
return first == null;
}
public int size() {
return N;
}
public void push(Item item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
N++;
}
public Item pop() {
if (empty()) {
return null;
}
Item item = first.item;
first = first.next;
N--;
return item;
}
private class Node {
Item item;
Node next;
}
}
2、queue
java语言实现queue。
package kb.algorithm;
public class Queue<Item> {
private Node first;
private Node last;
private int N;
public boolean empty() {
return first == null;
}
public int size() {
return N;
}
public void enqueue(Item item) {
Node oldLast = last;
last = new Node();
last.item = item;
last.next = null;
if (empty()) {
first = last;
} else {
oldLast.next = last;
}
N++;
}
public Item dequeue() {
if (empty()) {
return null;
}
Item item = first.item;
first = first.next;
if (empty()) {
last = null;
}
N--;
return item;
}
private class Node {
Item item;
Node next;
}
}
作者:iBrake
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.