队列(链式存储)JAVA代码
publicclassLinkQueue<T>{//结点类publicclassNode{public T data;publicNode next;publicNode(T obj,Node next){this.data = obj;this.next = next;}}privateNode head,front,rear;publicLinkQueue(){head =newNode(null,null);front = rear = head;size =0;}//从队尾入队publicvoid add(T t){Node s =newNode(t,null);rear.next = s;rear = s;size++;//队列长度+1}//从队头出队public T poll() throws Exception{if(rear == front)thrownewException("under flow!");Node temp = front.next; //暂存队首,以便返回front.next = front.next.next;if(front.next == null) //最后一个元素出队:还要对队尾处理rear = front;return temp.data;}public boolean isEmpty(){return front == rear;}}
LinkQueue<String> q =newLinkQueue<String>();q.add("a");q.add("b");q.add("c");q.add("d");q.add("e");q.add("f");q.add("g");q.add("h");q.add("i");q.add("j");q.add("k");q.add("l");q.add("m");while(!q.isEmpty()){String temp = q.poll();System.out.print(temp);}
输出
abcdefghijklm

浙公网安备 33010602011771号