Java LinkedList - 노드 연결 3
노드와 연결을 활용해 다양한 기능 만들기
직접 구현한 Node 클래스에서 몇 가지 조회 기능을 추가하자
- 모든 노드 탐색
- 마지막 노드 가져오기
- Index로 노드 조회
- 노드에 데이터 추가
public class Main {
public static void main(String[] args) {
// 노드 생성하고 연결하기: A -> B -> C
Node first = new Node("A");
first.next = new Node("B");
first.next.next = new Node("C");
System.out.println(first);
System.out.println("모든 노드 탐색");
printAll(first);
System.out.println("마지막 노드 가져오기");
Node last = getLastNode(first);
System.out.println("getLastNode = " + last.item);
System.out.println("인덱스로 노드 조회하기");
int index = 2;
Node iNode = getNode(first, index);
System.out.println("Find getNode = " + iNode.item);
System.out.println("새로운 데이터 노드 추가하기");
add(first, "D");
System.out.println(first);
}
private static void printAll(Node node) {
Node n = node;
while (n != null) {
System.out.println(n.item);
n = n.next;
}
}
private static Node getLastNode(Node node) {
Node n = node;
while (n.next != null) {
n = n.next;
}
return n; // n.next == null // 마지막 노드
}
private static Node getNode(Node node, int index) {
Node n = node;
for (int i = 0; i < index; i++) {
n = n.next;
}
return n;
}
private static void add(Node node, String param) {
Node lastNode = getLastNode(node);
lastNode.next = new Node(param);
}
}
[A->B->C]
모든 노드 탐색
A
B
C
마지막 노드 가져오기
getLastNode = C
인덱스로 노드 조회하기
Find getNode = C
새로운 데이터 노드 추가하기
[A->B->C->D]
기능이 올바르게 동작하는지 확인해보자.
printAll(Node node)
- 다음 노드가 없을 때까지 출력한다.
getLastNode()
- 마지막 노드를 조회로 가져온다.
- 반환되는 노드는 마지막 노드의 참조 값이다.
- Node.next 참조 값이 null 인 경우 노드의 끝을 나타낸다.
getNode(Node node, int index)
- 인덱스로 특정 노드로 찾는다.
- n = n.next 인덱스만큼 반복하여 n 의 노드 객체로 반환한다.
- 인덱스만큼 반복해서 찾은 노드는 원하는 노드로 반환한다.
add(Node node, String param)
- 마지막 노드를 가져오는 메소드 getLastNode() 호출한다.
- 데이터를 입력한 것으로 새로운 인스턴스 생성하고 기존 마지막 노드와 서로 연결한다.
정리
- 노드는 내부의 데이터와 다음 노드에 대한 참조를 갖고 있다.
- 노드의 노드로 참조로 통해 연결하므로 Link, 링크로 설명한다.
- 데이터 추가 시 동적으로 필요한 만큼 노드를 만들어 연결한다. 배열과 다르게 메모리 낭비가 없다.
- next 필드를 통한 참조 값을 보관하므로 배열과 다르게 오버헤드와 메모리 낭비가 있을 수 있다.
각각 노드들이 리스트로 서로 연결한 것이 연결리스트(LinkedList)라 한다.