package org.blog.test;
public class TestApplication {
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.add("1");
myLinkedList.add("2");
myLinkedList.add("3");
myLinkedList.add("4");
myLinkedList.add("5");
myLinkedList.add(2, "2.5");
myLinkedList.remove(3);
for (int i = 0; i < myLinkedList.size(); i++) {
System.out.println(myLinkedList.get(i).getData());
}
}
}
class MyLinkedList {
private Node head;
private Node tail;
private int size;
public MyLinkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
public void addFirst(Object data) {
Node myNode = new Node(data);
if (this.size == 0) {
this.head = myNode;
this.tail = myNode;
} else {
myNode.next = head;
head.prev = myNode;
this.head = myNode;
}
size++;
}
public void add(Object data) {
if (this.size() == 0) {
addFirst(data);
} else {
Node newNode = new Node(data);
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
size++;
}
}
public void add(int index, Object data) {
if (index == 0) {
addFirst(data);
} else if (index == this.size) {
add(data);
} else {
Node newNode = new Node(data);
Node currentNode = get(index);
newNode.prev = currentNode.prev;
newNode.prev.next = newNode;
newNode.next = currentNode;
currentNode.prev = newNode;
size++;
}
}
public void removeFirst() {
this.head = this.head.next;
this.head.prev = null;
this.size--;
}
public void remove() {
this.tail = this.tail.prev;
this.tail.next = null;
size--;
}
public void remove(int index) {
if (index == 0) {
removeFirst();
} else if (index == this.size - 1) {
remove();
} else {
Node prevNode = get(index - 1);
Node nextNode = get(index + 1);
prevNode.next = nextNode;
nextNode.prev = prevNode;
size--;
}
}
public Node get(int index) {
if (index < (this.size / 2)) {
Node ret = this.head;
for (int i = 0; i < index; i++) {
ret = ret.next;
}
return ret;
} else {
Node ret = this.tail;
for (int i = size - 1; i > index; i--) {
ret = ret.prev;
}
return ret;
}
}
public int size() {
return this.size;
}
class Node {
private Object data;
private Node prev;
private Node next;
public Node(Object data) {
this.data = data;
this.prev = null;
this.next = null;
}
public Object getData() {
return this.data;
}
}
}
- output
1 2 2.5 4 5 Process finished with exit code 0
댓글 없음 :
댓글 쓰기