package com.interview;
public class LinkQueue<T> {
class Node<T> {
private T data;
private Node<T> next;
public Node() {
this.data = null;
this.next = null;
}
public Node(T data) {
this.data = data;
this.next = null;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
private Node<T> head;
private Node<T> tail;
public LinkQueue() {
this.head = null;
this.tail = null;
}
// 入队
public boolean inQueue(T t) {
// 生成一个新的节点。
Node<T> p = new Node<T>(t);
if (head == null) {
head = p;
tail = p;
} else {
tail.next = p;
tail = tail.next;
}
return true;
}
public T outQueue() {
if (head == null)
return null;
else {
T t = head.getData();
head = head.getNext();
return t;
}
}
// 查对头
public T peek() {
if (head == null)
return null;
else {
return head.getData();
}
}
// 判空
public boolean isEmpty() {
return head == null;
}
// 分别用数组与链表实现栈 push pop
}
进行测试
package test.interview;
import com.interview.LinkQueue;
public class LinkQueueTest {
public static void main(String[] args) {
LinkQueue<Integer> linkQueue=new LinkQueue<Integer>();
for (int i = 0; i < 10; i++) {
linkQueue.inQueue(i);
System.out.println(linkQueue.peek());
}
for (int i = 0; !linkQueue.isEmpty(); i++) {
System.out.println(linkQueue.peek()+" "+linkQueue.outQueue());
}
}
}
0
0
0
0
0
0
0
0
0
0
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9