public class LinkedList {
Node head;
int size = 0;
class Node{
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
size++;
}
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
size++;
}else{
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
size++;
}
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
System.out.println("총 리스트 크기는: "+ size);
}
public void insert(int data, int position) {
Node newNode = new Node(data);
if (position == 0) {
addFirst(data);
}
Node temp = head;
for (int i = 0; i < position - 1; i++) {
if (temp == null) {
System.out.println("position에 벗어난것같다.");
}
temp = temp.next;
}
newNode.next = temp.next;
temp.next = newNode;
size++;
}
public void delete(int key) {
Node temp = head;
Node prev = null;
if (temp == null) {
System.out.println("리스트가 비어 있습니다.");
}
if (temp != null && temp.data == key) {
head = temp.next;
size--;
return;
}
while (temp != null && temp.data != key) {
prev = temp;
temp = temp.next;
}
if (temp == null) {
System.out.println("노드를 찾을 수 없습니다. " +key);
}
prev.next = temp.next;
}
public boolean search(int key) {
Node temp = head;
while (temp != null) {
if (temp.data == key) {
return true;
}
temp = temp.next;
}
return false;
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.addLast(3);
linkedList.addFirst(1);
linkedList.addFirst(2);
linkedList.addLast(4);
linkedList.addLast(5);
linkedList.printList();
linkedList.insert(8,2);
linkedList.printList();
linkedList.insert(15,4);
linkedList.printList();
linkedList.delete(2);
linkedList.printList();
}
}