前言
学习了单链表和队列,我们不妨用单链表来实现一下队列
单链表不做过多赘述,这里重新复习一下队列
1.先进先出
2.队头删除,队尾增加
算法分析
代码分析
1.实现任意数据类型的结点类
public static class Node<V>{
public V value;
public Node<V> next;
public Node(V v){
value=v;
next=null;
}
}
2.实现队列类
public static class MyQueue<V>{
private Node<V> head;
private Node<V> tail;
private int size;
public MyQueue(){
head=null;
tail=null;
size=0;
}
public boolean isEmpty(){
return size==0;
}
public int size(){
return size;
}
public void offer(V value){
Node<V> cur=new Node<V>(value);
if(tail==null){
head=cur;
tail=cur;
}else{
tail.next=cur;
tail=cur;
}
size++;
}
public V Pop(){
V ans=null;
if(head!=null){
ans=head.value;
head=head.next;
size--;
}
if(head==null){
tail=null;
}
return ans;
}
}
3.测试
public static void main(String[] args) {
MyQueue<Integer> myQueue=new MyQueue<Integer>();
myQueue.offer(1);
myQueue.offer(2);
myQueue.offer(3);
myQueue.offer(4);
int ans1=myQueue.Pop();
int ans2=myQueue.Pop();
int ans3=myQueue.Pop();
int ans4=myQueue.Pop();
System.out.println(ans1);
System.out.println(ans2);
System.out.println(ans3);
System.out.println(ans4);
}
4.完整代码
package List;
public class 用单链表实现队列 {
public static class Node<V>{
public V value;
public Node<V> next;
public Node(V v){
value=v;
next=null;
}
}
public static class MyQueue<V>{
private Node<V> head;
private Node<V> tail;
private int size;
public MyQueue(){
head=null;
tail=null;
size=0;
}
public boolean isEmpty(){
return size==0;
}
public int size(){
return size;
}
public void offer(V value){
Node<V> cur=new Node<V>(value);
if(tail==null){
head=cur;
tail=cur;
}else{
tail.next=cur;
tail=cur;
}
size++;
}
public V Pop(){
V ans=null;
if(head!=null){
ans=head.value;
head=head.next;
size--;
}
if(head==null){
tail=null;
}
return ans;
}
}
public static void main(String[] args) {
MyQueue<Integer> myQueue=new MyQueue<Integer>();
myQueue.offer(1);
myQueue.offer(2);
myQueue.offer(3);
myQueue.offer(4);
int ans1=myQueue.Pop();
int ans2=myQueue.Pop();
int ans3=myQueue.Pop();
int ans4=myQueue.Pop();
System.out.println(ans1);
System.out.println(ans2);
System.out.println(ans3);
System.out.println(ans4);
}
}
看懂了这篇文章,我相信你已经可以独立的完成单链表实现队列了,即是复习了队列,又加强了单链表,快去练练吧!!!