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

93 lines
2.5 KiB
Java
Raw Normal View History

2021-12-25 09:02:00 +00:00
/*
* The MIT License (MIT)
*
2022-03-13 08:05:01 +00:00
* Copyright © 2021 xrv <xrv@live.com>
2021-12-25 09:02:00 +00:00
*
* 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>
* O(n)
*
* @author ehlxr
* @since 2021-12-25 16:02.
*/
2021-12-25 15:23:33 +00:00
public class LinkedListQueue<T> {
private Node<T> head;
2021-12-25 09:02:00 +00:00
public static void main(String[] args) {
2021-12-25 15:23:33 +00:00
LinkedListQueue<Integer> queue = new LinkedListQueue<>();
2021-12-25 09:02:00 +00:00
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(n)
*/
2021-12-25 15:23:33 +00:00
public boolean enqueue(T item) {
Node<T> node = new Node<T>(item, null);
2021-12-25 09:02:00 +00:00
if (head == null) {
head = node;
return true;
}
// 找到队尾
2021-12-25 15:23:33 +00:00
Node<T> tail = head;
2021-12-25 09:02:00 +00:00
while (tail.getNext() != null) {
tail = tail.getNext();
}
tail.setNext(node);
return true;
}
/**
*
*/
2021-12-25 15:23:33 +00:00
public T dequeue() {
2021-12-25 09:02:00 +00:00
if (head == null) {
return null;
}
2021-12-25 15:23:33 +00:00
T val = head.getVal();
2021-12-25 09:02:00 +00:00
head = head.getNext();
return val;
}
2021-12-25 15:23:33 +00:00
public Node<T> getData() {
2021-12-25 09:02:00 +00:00
return head;
}
}