チーム
1.コンセプト
- キュー:一方の端でのみデータを挿入し、もう一方の端でデータを削除できる特別な線形テーブル。キューにはFIFO(First In First Out)があります。挿入操作の終わりはテール/リアと呼ばれます。キューの:削除操作の終了は、キューの先頭(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ヘッド要素を取得する
- アイデア:チームのヘッド要素を取得するのは比較的簡単です。ヘッドがある限り、ヘッドノードの値を直接返します。
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());
}
}