1. 구현 기능
2. 구현 코드
public class MyListNode {
private String data;
public MyListNode next;
public MyListNode(){
data = null;
next = null;
}
public MyListNode(String data){
this.data = data;
this.next = null;
}
public MyListNode(String data, MyListNode next){
this.data = data;
this.next = next;
}
public String getData() {
return data;
}
}
public class MyLinkedList {
private MyListNode head;
public MyListNode tempNode;
public int count;
public MyLinkedList() {
head = null;
count = 0;
}
public MyListNode addNode(String data) {
MyListNode newNode = new MyListNode(data);
if(head == null) {
head = newNode;
newNode.next = null;
}
else {
tempNode = head;
while(tempNode.next != null) {
tempNode = tempNode.next;
}
tempNode.next = newNode;
}
count++;
return newNode;
}
public void insertNode(int pos, String data) {
MyListNode newNode;
if(pos < 0 || pos > count) {
System.out.println("인덱스 에러!");
return;
}
if(pos == 0){
newNode = new MyListNode(data);
newNode.next = head;
head = newNode;
}
else {
newNode = new MyListNode(data);
tempNode = head;
for(int i = 0; i < pos-1; i++) {
tempNode = tempNode.next;
}
newNode.next = tempNode.next;
tempNode.next = newNode;
}
count++;
}
public void removeNode(int pos) {
if (isEmpty()) {
System.out.println("삭제할 요소 없음!");
return;
}
if (pos < 0 || pos > count-1) {
System.out.println("index 에러!");
return;
}
else if(pos == 0) {
head = head.next;
}
else {
tempNode = head;
for(int i = 0; i < pos-1;i++) {
tempNode = tempNode.next;
}
tempNode.next = tempNode.next.next;
}
count--;
}
public String getElement(int pos) {
if(pos < 0 || pos > count) {
System.out.println("인덱스 에러!");
return null;
}
tempNode = head;
for (int i =0; i < pos; i++) {
tempNode = tempNode.next;
}
return tempNode.getData();
}
public void printAll() {
if(isEmpty()) {
System.out.println("출력할 요소 없음!");
return;
}
tempNode = head;
while(tempNode != null) {
System.out.println(tempNode.getData());
tempNode = tempNode.next;
}
public boolean isEmpty() {
if(count == 0) {
return true;
}
else {
return false;
}
}
public int getSize() {
return count;
}
public MyListNode getHead() {
return head;
}
}