team
1. Concept
Queue : A special linear table that only allows inserting data at one end and deleting data at the other end. The queue has FIFO (First In First Out) into the queue: the end of the insert operation is called the tail/rear ) Out of the queue: The end of the delete operation is called the head of the queue (Head/Front);
2. Realize
Realize queue with singly linked list
2.1 Join the team
First judge whether there is an element before, if there is no element, it is directly used as the head;
If there are elements before, it is equivalent to tail interpolation;
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 Departure
First determine whether there are elements in the queue;
If there are elements, because the queue is first in, first out, the head node is directly used as the new head;
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 Get the head element
Idea: It is relatively simple to get the head element of the team, as long as there is a head, directly return the value of the head node;
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. Complete source code
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 ( ) ) ;
}
}