알고리즘 문제 4 단일 체인 테이블로 대기열 실현

package com.interview;

public class LinkQueue<T> {
     
	class Node<T> {
     
		private T data;
		private Node<T> next;

		public Node() {
     
			this.data = null;
			this.next = null;
		}

		public Node(T data) {
     
			this.data = data;
			this.next = null;
		}

		public T getData() {
     
			return data;
		}

		public void setData(T data) {
     
			this.data = data;
		}

		public Node<T> getNext() {
     
			return next;
		}

		public void setNext(Node<T> next) {
     
			this.next = next;
		}

	}

	private Node<T> head;
	private Node<T> tail;

	public LinkQueue() {
     
		this.head = null;
		this.tail = null;
	}

	//  

	public boolean inQueue(T t) {
     
		//  。
		Node<T> p = new Node<T>(t);
		if (head == null) {
     
			head = p;
			tail = p;
		} else {
     

			tail.next = p;
			tail = tail.next;
		}
		return true;
	}

	public T outQueue() {
     
		if (head == null)
			return null;
		else {
     
			T t = head.getData();
			head = head.getNext();
			return t;
		}

	}

	//  
	public T peek() {
     

		if (head == null)
			return null;
		else {
     
			return head.getData();
		}
	}

	//  

	public boolean isEmpty() {
     
		return head == null;
	}

	//   push pop
}


테스트를 진행하다
package test.interview;

import com.interview.LinkQueue;

public class LinkQueueTest {
     
    public static void main(String[] args) {
     
		
    	
		LinkQueue<Integer> linkQueue=new LinkQueue<Integer>();
        for (int i = 0; i < 10; i++) {
     
        	linkQueue.inQueue(i);
        	System.out.println(linkQueue.peek());
		}
        
        for (int i = 0; !linkQueue.isEmpty(); i++) {
     
			System.out.println(linkQueue.peek()+"  "+linkQueue.outQueue());
			
		}
	}
}

0
0
0
0
0
0
0
0
0
0
0  0
1  1
2  2
3  3
4  4
5  5
6  6
7  7
8  8
9  9

좋은 웹페이지 즐겨찾기