队
1.概念
队列 :只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out) 入队列:进行插入操作的一端称为队尾(Tail/Rear) 出队列:进行删除操作的一端称为队头(Head/Front);
2.实现
2.1入队
首先判断之前有没有元素,如果没有元素,就直接作为头; 如果之前已经有元素,就相当于尾插法;
public void offer ( int val) {
Node node = new Node ( val) ;
if ( this . head == null) {
this . head = node;
this . tail = node;
return ;
}
this . tail. next = node;
this . tail = node;
}
2.2出队
首先判断队列里面是否有元素; 如果有元素,因为队列先进先出,所以直接将头节点作为新的头就好;
public int poll ( ) {
if ( this . head == null) {
throw new RuntimeException ( "队列为空\n" ) ;
}
int oldData = this . head. val;
if ( this . head. next == null) {
this . head = null;
this . tail = null;
} else {
this . head = this . head. next;
}
return oldData;
}
2.3获取队头元素
思路:获取队头元素就比较简单,只要有头,直接返回head节点的值;
public int peek ( ) {
if ( this . head == null) {
throw new RuntimeException ( "队列为空\n" ) ;
}
return this . head. val;
}
public boolean isEmpty ( ) {
if ( this . head == null) {
return true ;
}
return false ;
}
3.完整源码
import java. util. LinkedList;
import java. util. Queue;
class Node {
public int val;
public Node next;
public Node ( int val) {
this . val = val;
}
}
class MyQueue {
public Node head;
public Node tail;
public void offer ( int val) {
Node node = new Node ( val) ;
if ( this . head == null) {
this . head = node;
this . tail = node;
return ;
}
this . tail. next = node;
this . tail = node;
}
public int poll ( ) {
if ( this . head == null) {
throw new RuntimeException ( "队列为空\n" ) ;
}
int oldData = this . head. val;
if ( this . head. next == null) {
this . head = null;
this . tail = null;
} else {
this . head = this . head. next;
}
return oldData;
}
public int peek ( ) {
if ( this . head == null) {
throw new RuntimeException ( "队列为空\n" ) ;
}
return this . head. val;
}
public boolean isEmpty ( ) {
if ( this . head == null) {
return true ;
}
return false ;
}
}
public class TestDemo3 {
public static void main ( String[ ] args) {
MyQueue myQueue = new MyQueue ( ) ;
myQueue. offer ( 1 ) ;
myQueue. offer ( 2 ) ;
myQueue. offer ( 3 ) ;
myQueue. offer ( 4 ) ;
System. out. println ( myQueue. peek ( ) ) ;
System. out. println ( myQueue. poll ( ) ) ;
System. out. println ( myQueue. poll ( ) ) ;
System. out. println ( myQueue. poll ( ) ) ;
System. out. println ( myQueue. poll ( ) ) ;
}
}