当前位置: 代码迷 >> 综合 >> 链表实现队列(先进先出)
  详细解决方案

链表实现队列(先进先出)

热度:43   发布时间:2023-12-02 18:22:34.0

定义类:

public class ListNode {int val;ListNode next;public ListNode(int val) {this.val = val;this.next = null;}public int getVal() {return val;}public void setVal(int val) {this.val = val;}public ListNode getNext() {return next;}public void setNext(ListNode next) {this.next = next;}
}
static ListNode head = null;public static void main(String[] args) {insert(3);insert(2);insert(1);get();get();get();get();}public static void insert(int val) {ListNode node = new ListNode(val);//为空,让头节点为nodeif (head == null) {head = node;return;}ListNode temp = head;//尾插,放在后面while(temp.next!=null){temp=temp.next;}temp.next=node;}public static void get() {if (head != null) {System.out.println(head.val);head = head.next;} else {System.out.println("队列空了");}}

输出结果: