[자료구조] 07 과제

안우진·2024년 5월 9일
1

자료구조

목록 보기
10/12

[CQueue]

import java.util.NoSuchElementException;

public class CQueue<E> {
	
	protected Node<E> rear; 
	protected int size;
	
	public CQueue () { 
		rear = null;
		size = 0;
	}
	
	public void insert(E newItem) {
		Node<E> node = new Node<>(newItem);
		if (isEmpty()) {
			node.setNext(node);
			rear = node;
			size = 1;
			return;
		}
		node.setNext(rear.getNext());
		rear.setNext(node);
		rear = node;
		size++;
	}
	
	public E delete() {
		if (isEmpty()) throw new NoSuchElementException();
		Node<E> target = rear.getNext();
		E item = target.getData();
		rear.setNext(target.getNext());
		size--;
		if (isEmpty()) rear = null;
		return item;
	}
	
	public boolean isEmpty() {
		return size == 0 || rear == null;
	}
}

[Assignment]

import java.util.NoSuchElementException;

public class Assignment {
	
	private final String[] inputs;
	
	public Assignment(String[] inputs) {
		this.inputs = inputs;
	}
	
	public void assignment() {
		CQueue<Integer> cQueue = new CQueue<>();
		
		for (String e : inputs) {
			if (e.equals("i")) continue;
			if (e.equals("d")) {
				try {
					System.out.print(cQueue.delete() + " ");
				} catch (NoSuchElementException exception) {
					System.out.print("empty ");
				}
				continue;
			}
			cQueue.insert(Integer.parseInt(e));
		}
		System.out.println();
	}
}

0개의 댓글