[数据结构]队列的实现,单链表

迷南。 2023-03-03 08:39 69阅读 0赞

I’m Shendi

下面是队列的代码,使用的单链表,先进先出

  1. /**
  2. * 队列,单链表.
  3. * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
  4. * @version 1.0
  5. */
  6. public class 队列<E> {
  7. private static class Node<E> {
  8. E data;
  9. Node<E> next;
  10. public Node (E data, Node<E> next) {
  11. this.data = data;
  12. this.next = next;
  13. }
  14. }
  15. private Node<E> front;
  16. private Node<E> rear;
  17. public void push(E e) {
  18. if (front == null) {
  19. front = new Node<E>(e, null);
  20. rear = front;
  21. } else {
  22. rear.next = new Node<E>(e, null);
  23. rear = rear.next;
  24. }
  25. }
  26. public E pop() {
  27. if (front == null) return null;
  28. E data = front.data;
  29. front = front.next;
  30. return data;
  31. }
  32. public static void main(String[] args) {
  33. 队列<Integer> queue = new 队列<>();
  34. queue.push(1);
  35. queue.push(2);
  36. queue.push(3);
  37. for (int i = 0;i < 3;i++) {
  38. System.out.println(queue.pop());
  39. }
  40. for (int i = 0;i < 3;i++) {
  41. System.out.println(queue.pop());
  42. }
  43. }
  44. }

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读