노드 클래스
노드 클래스는 내부에 저장할 데이터인 item
과, 다음으로 연결할 노드의 참조인 next
를 가진다
public class Node {
Object item;
Node next;
}
연결된 노드를 찾는 방법
Node first
를 통해 첫 번째 노드를 구할 수 있다.node.next
를 호출하면 두 번째 노드를 구할 수 있다.node.next
를 호출하면 세 번째 노드를 구할 수 있다.node.next.next
를 호출하면 세 번째 노드를 구할 수 있다.모든 노드 탐색하기
Node x = first;
while (x != null) {
System.out.println(x.item);
x = x.next;
}
Node x
는 처음 노드부터 순서대로 이동하면서 모든 노드를 가리킨다. 처음에 Node x
는 x01
을 참조한다. 그리고 while
문을 통해 반복해서 다음 노드를 가리킨다. while
문은 다음 노드가 없을 때 까지 반복한다. Node.next
의 참조값이 null
이면 노드의 끝이다
노드와 연결을 활용해서 다양한 기능을 만들어보자
모든 노드 탐색하기
마지막 노드 조회하기
특정 index의 노드 조회하기
노드에 데이터 추가하기
public class Node {
Object item;
Node next;
public Node(Object item) {
this.item = item;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node x = this;
sb.append("[");
while (x != null) {
sb.append(x.item);
if (x.next != null) {
sb.append("->");
}
x = x.next;
}
sb.append("]");
return sb.toString();
}
}
public class NodeMain3 {
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);
//마지막 노드 조회하기
Node lastNode = getLastNode(first);
System.out.println("lastNode = " + lastNode);
//특정 index의 노드 조회하기
int index = 2;
Node index2Node = getNode(first, index);
System.out.println("index2Node = " + index2Node.item);
//데이터 추가하기
System.out.println("데이터 추가하기");
add(first, "D");
System.out.println(first);
add(first, "E");
System.out.println(first);
add(first, "F");
System.out.println(first);
}
private static void printAll(Node node) {
Node x = node;
while (x != null) {
System.out.println(x.item);
x = x.next;
}
}
private static Node getLastNode(Node node) {
Node x = node;
while (x.next != null) {
x = x.next;
}
return x;
}
private static Node getNode(Node node, int index) {
Node x = node;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x;
}
private static void add(Node node, String param) {
Node lastNode = getLastNode(node);
lastNode.next = new Node(param);
}
}