휴지통/알고리즘 & 자료구조
Single Linked List
by 신재권
2021. 7. 14.
package review1;
public class SingleLinkedList<T> {
//head ( 첫번째 요소를 가리키는 노드)
Node<T> head = null;
//데이터 추가 구현
public void addNode(T data){
if(head == null){ //첫번째 데이터라면
head = new Node<T>(data);
}else{ //두번째 이후 데이터라면
Node<T> node = this.head;
while(node.next != null){ //순회
node = node.next;
}
node.next = new Node<T>(data);
}
}
//전체 출력
public void printAll(){
if(head != null){
Node<T> node = this.head;
System.out.print("["+node.data+", ");
while(node.next != null){
node = node.next;
System.out.print(node.data+", ");
}
System.out.println("]");
}
}
//특정 데이터 찾기
public Node<T> search(T data){
if(this.head == null){
return null;
}else{
Node<T> node = this.head;
while(node.next != null){
if(node.data == data){
return node;
}else{
node = node.next;
}
}
return null; //찾기 실패시 반환
}
}
//데이터 중간 삽입
public void insertNode(T data, T isData){ // isData뒤에 data 삽입
Node<T> searchedNode = this.search(isData); //isData의 위치를 먼저 찾는다.
if(searchedNode == null){ //찾는 데이터가 존재하지 않으면, 맨 뒤에 데이터 추가
this.addNode(data);
}else{
Node<T> nextNode= searchedNode.next; //원래 isData의 next 노드를 임시저장
searchedNode.next = new Node<T>(data); //새로운 노드를 isData의 next로 바꿈
searchedNode.next.next = nextNode; //isData의 next,next 즉 새로운 노드의 next를 임시저장한 노드를 가리키게함
}
}
//특정 노드 삭제
public boolean deleteNode(T data){
if(this.head == null){
return false;
}else{
Node<T> node = this.head;
if(node.data == data){
this.head = this.head.next; //head가 삭제되면 head가 가리키는 next 노드를 head로 만듬
return true;
}else{
while(node.next != null){
if(node.next.data == data){
node.next = node.next.next;
return true;
}
node = node.next;
}
return false;
}
}
}
// SingleLinkedList는 단일 방향으로밖에 못감
public static void main(String[] args) {
SingleLinkedList<Integer> linked_list = new SingleLinkedList<Integer>();
linked_list.addNode(3);
System.out.println(linked_list.head.data); //3
System.out.println();
linked_list.addNode(2);
linked_list.addNode(5);
linked_list.printAll();
linked_list.insertNode(4, 2); //2 뒤에 넣기
linked_list.insertNode(1, 8); //존재하지 않는 값뒤에 넣기
linked_list.printAll();
//[3, 2, 4, 5, 1, ]
//중간 노드 삭제
linked_list.deleteNode(4);
linked_list.printAll(); //[3, 2, 5, 1, ]
//헤드 노드 삭제
linked_list.deleteNode(3);
linked_list.printAll(); //[2, 5, 1, ]
//마지막 노드 삭제
linked_list.deleteNode(1);
linked_list.printAll(); //[2, 5, ]
}
}
class Node<T>{ //노드 클래스 선언
T data; //데이터
Node<T> next = null; //다음 요소를 가리킨다.
public Node(T data){
this.data= data;
}
}