image.png

    • 头结点删除元素,尾结点插入元素
    • 由于没有dummyHead, 要注意链表为空的情况
    1. package com.hoho.datastruture.queue;
    2. import com.hoho.datastruture.LinkedList.LinkedList;
    3. public class LinkedListQueue<E> implements Queue<E> {
    4. private class Node {
    5. public E e;
    6. public Node next;
    7. public Node(E e, Node next) {
    8. this.e = e;
    9. this.next = next;
    10. }
    11. public Node(E e) {
    12. this(e, null);
    13. }
    14. public Node() {
    15. this(null, null);
    16. }
    17. @Override
    18. public String toString() {
    19. return e.toString();
    20. }
    21. }
    22. private Node head, tail;
    23. private int size;
    24. public LinkedListQueue() {
    25. this.head = null;
    26. this.tail = null;
    27. this.size = 0;
    28. }
    29. @Override
    30. public void enqueue(E e) {
    31. //尾部进队列
    32. if (tail == null) {
    33. tail = new Node(e);
    34. head = tail;
    35. } else {
    36. tail.next = new Node(e);
    37. tail = tail.next;
    38. }
    39. size++;
    40. }
    41. @Override
    42. public E dequeue() {
    43. if (isEmpty()) {
    44. throw new IllegalArgumentException("队列为空,无法出队");
    45. }
    46. Node retNode = head;
    47. head = head.next;
    48. retNode.next = null;
    49. if (head == null) {
    50. tail = null;
    51. }
    52. size--;
    53. return retNode.e;
    54. }
    55. @Override
    56. public E getFront() {
    57. if (isEmpty()) {
    58. throw new IllegalArgumentException("队列为空,无法出队");
    59. }
    60. return head.e;
    61. }
    62. @Override
    63. public int getSize() {
    64. return size;
    65. }
    66. @Override
    67. public boolean isEmpty() {
    68. return size == 0;
    69. }
    70. @Override
    71. public String toString() {
    72. StringBuilder res = new StringBuilder();
    73. res.append("Queue: front ");
    74. Node current = head;
    75. while (current != null) {
    76. res.append(current + " -> ");
    77. current = current.next;
    78. }
    79. res.append("NULL tail");
    80. return res.toString();
    81. }
    82. }