budd/budd-common/src/main/java/io/github/ehlxr/datastructure/queue/LinkedListQueue2.java

95 lines
2.6 KiB
Java
Raw Normal View History

2021-12-25 09:02:00 +00:00
/*
* The MIT License (MIT)
*
* Copyright © 2021 xrv <xrg@live.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.ehlxr.datastructure.queue;
2021-12-25 14:49:21 +00:00
import io.github.ehlxr.datastructure.Node;
2021-12-25 09:02:00 +00:00
/**
*
* <p>
* tail O(1)
*
* @author ehlxr
* @since 2021-12-25 16:48.
*/
public class LinkedListQueue2 {
2021-12-25 14:49:21 +00:00
private Node<Integer> head = null;
private Node<Integer> tail = null;
2021-12-25 09:02:00 +00:00
public static void main(String[] args) {
LinkedListQueue2 queue = new LinkedListQueue2();
for (int i = 0; i < 6; i++) {
System.out.println(queue.enqueue(i));
}
for (int i = 0; i < 6; i++) {
queue.getData().print();
System.out.println(queue.dequeue());
}
System.out.println(queue.dequeue());
}
/**
*
* O(1)
*/
public boolean enqueue(Integer item) {
2021-12-25 14:49:21 +00:00
Node<Integer> node = new Node<Integer>(item, null);
2021-12-25 09:02:00 +00:00
if (tail == null) {
head = node;
tail = node;
return true;
}
tail.setNext(node);
tail = node;
return true;
}
/**
*
*/
public Integer dequeue() {
if (head == null) {
return null;
}
Integer val = head.getVal();
head = head.getNext();
// 如果队列为空了,需要把 tail 置空
if (head == null) {
tail = null;
}
return val;
}
2021-12-25 14:49:21 +00:00
public Node<Integer> getData() {
2021-12-25 09:02:00 +00:00
return head;
}
}