public class LinkedListTest {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addItem("test1");
list.addItem("test2");
list.addItem("test3");
list.addItem(1, "test1.5");
System.out.println(list.getItem(0));
System.out.println(list.getItem(1));
System.out.println(list.getItem(2));
System.out.println(list.getItem(3));
list.deleteItem(0);
System.out.println(list.getItem(0));
System.out.println(list.getItem(1));
System.out.println(list.getItem(2));
System.out.println(list.size());
}
}
public class Node {
private Node next = null;
private String item = null;
public Node(String item, Node node) {
this.item = item;
this.next = node;
}
public Node getNext() {
return next;
}
public void setNext(Node node) {
this.next = node;
}
public String getItem() {
return item;
}
}
public class LinkedList {
private Node first = null;
private Node last = null;
private int size = 0;
public void addFirst(String item) {
Node newNode = new Node(item, first);
first = newNode;
size++;
if(first.getNext() == null) {
last = first;
}
}
public void addItem(String item) {
if(first == null) {
addFirst(item);
} else {
Node newNode = new Node(item, null);
last.setNext(newNode);
last = newNode;
size++;
}
}
public void addItem(int index, String item) {
if(index == 0) {
addFirst(item);
} else {
Node tempNode1 = getNode(index - 1);
Node tempNode2 = tempNode1.getNext();
Node newNode = new Node(item, tempNode2);
tempNode1.setNext(newNode);
size++;
}
}
public String getItem(int index) {
return getNode(index).getItem();
}
public int size() {
return size;
}
public void deleteItem(int index) {
if(first == null) {
throw new IndexOutOfBoundsException("연결리스트에 생성된 값이 존재하지 않습니다.");
} else if(index == 0) {
Node tempNode1 = getNode(index);
first = (1 < size)?tempNode1.getNext():null;
if(first != null) size--;
} else {
Node tempNode1 = getNode(index - 1);
Node tempNode2 = getNode(index);
tempNode1.setNext(tempNode2.getNext());
size--;
}
}
public Node getNode(int index) {
Node node = first;
if(size <= index || index < 0) {
throw new IndexOutOfBoundsException("연결리스트의 길이를 초과한 index값이 입력되었습니다.");
}
for(int i = 0; i < index; i++) {
node = node.getNext();
}
return node;
}
}