Circular Doubly Linked List
자료구조 PDF와 달리 head는 dummy가 아님.
import java.util.NoSuchElementException;
public class CDList {
protected DNode head;
protected int size;
public void insert(int newItem) {
DNode newNode = new DNode(newItem);
if (isEmpty()) {
head = newNode;
head.setPrevious(head);
head.setNext(head);
size = 1;
return;
}
DNode previous = head.getPrevious();
previous.setNext(newNode);
head.setPrevious(newNode);
newNode.setNext(head);
newNode.setPrevious(previous);
head = newNode;
size++;
}
public void delete() {
if (isEmpty()) return;
DNode target = head.getPrevious();
DNode previous = target.getPrevious();
previous.setNext(head);
head.setPrevious(previous);
target.setNext(null);
target.setPrevious(null);
size--;
if (size == 0) head = null;
}
public void printall() {
if (isEmpty()) {
throw new NoSuchElementException();
}
DNode p = head;
for(int i=0; i<size; i++) {
System.out.print(p.getData() + " ");
p = p.getNext();
}
System.out.println();
}
public boolean isEmpty() {
return head == null;
}
}
public class Assignment {
private final String[] inputs;
public Assignment(String[] inputs) {
this.inputs = inputs;
}
public void assignment() {
CDList cdList = new CDList();
for (String e : inputs) {
if (e.equals("i")) continue;
if (e.equals("d")) {
cdList.delete();
continue;
}
cdList.insert(Integer.parseInt(e));
}
cdList.printall();
}
}