java 基于链表的队列 队列
程序员文章站
2022-04-27 15:13:37
...
public class QueueLinked<T> { private class Node<T> { T data; Node<T> next; Node<T> pre; public Node(T data) { this.data = data; } } Node<T> head = null; Node<T> tail = null; public void add(T data) { Node<T> node = new Node<T>(data); if(head==null) { head = node; tail = node; }else { tail.next = node; node.pre = tail; tail = node; } } public T popTail() { if(tail==null) { return null; }else { Node<T> node = tail; tail = node.pre; if(tail!=null) { tail.next = null; } node.pre = null; return node.data; } } public T popHead() { if(head==null) { return null; }else { Node<T> node = head; head = node.next; if(head!=null) { head.pre = null; } node.next = null; return node.data; } } public int size() { int count = 0; Node<T> node = head; while(node!=null) { count++; node = node.next; } return count; } public static void main(String[] args) { QueueLinked<Message> queue = new QueueLinked<Message>(); Message message1 = new Message(); message1.setMethod("信息1"); queue.add(message1); Message message2 = new Message(); message2.setMethod("信息2"); queue.add(message2); System.out.println(queue.size()); Message message = null; while((message=queue.popTail())!=null) { System.out.println(message.getMethod()); } } }
下一篇: roketmq3.2.6