@XQF
2018-03-07T14:52:56.000000Z
字数 542
阅读 845
数据结构与算法
链表实在是太简单了。队列只需要维护链表的最后一个节点指针和头节点指针。
class ListNode<T> {T t;ListNode<T> next;public ListNode(T t) {this.t = t;}}class MyQueue<T> {ListNode<T> tail;ListNode<T> head;public MyQueue() {head = null;tail = null;}public boolean add(T t) {if (t == null) {return false;}ListNode<T> node = new ListNode<>(t);if (tail == null) {tail = node;head = tail;} else {tail.next = node;tail = tail.next;}return true;}public T peek() {return head.t;}public T remove() {T t = head.t;head = head.next;return t;}public int size() {ListNode<T> p = head;int counter = 0;while (p != null) {counter++;p = p.next;}return counter;}}
