[关闭]
@XQF 2018-03-07T22:52:56.000000Z 字数 542 阅读 720

如何使用链表实现队列

数据结构与算法


链表实在是太简单了。队列只需要维护链表的最后一个节点指针和头节点指针。

  1. class ListNode<T> {
  2. T t;
  3. ListNode<T> next;
  4. public ListNode(T t) {
  5. this.t = t;
  6. }
  7. }
  8. class MyQueue<T> {
  9. ListNode<T> tail;
  10. ListNode<T> head;
  11. public MyQueue() {
  12. head = null;
  13. tail = null;
  14. }
  15. public boolean add(T t) {
  16. if (t == null) {
  17. return false;
  18. }
  19. ListNode<T> node = new ListNode<>(t);
  20. if (tail == null) {
  21. tail = node;
  22. head = tail;
  23. } else {
  24. tail.next = node;
  25. tail = tail.next;
  26. }
  27. return true;
  28. }
  29. public T peek() {
  30. return head.t;
  31. }
  32. public T remove() {
  33. T t = head.t;
  34. head = head.next;
  35. return t;
  36. }
  37. public int size() {
  38. ListNode<T> p = head;
  39. int counter = 0;
  40. while (p != null) {
  41. counter++;
  42. p = p.next;
  43. }
  44. return counter;
  45. }
  46. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注