LinkedNodeList 알고리즘 (3)
단방향 LinkedList 의 끝에서 k번쨰 노드를 찾는 알고리즘을 구현하시오
- 단방향 LinkedList 의 끝에서 k번쨰 노드를 찾는 알고리즘을 구현하시오
2 -> 3 -> 1 -> 4 일 경우 k번째 노드를 찾는 알고리즘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Node {
int data;
Node next;
}
class LinkedList {
Node head;
LinkedList() {
head = new Node();
}
void append(int d) {
Node newNode = new Node();
newNode.data = d;
Node nowNode = head;
while (nowNode.next != null) {
nowNode = nowNode.next;
}
nowNode.next = newNode;
}
void delete(int d) {
Node nowNode = head;
while (nowNode.next != null) {
if (nowNode.next.data == d) {
nowNode.next = nowNode.next.next;
} else {
nowNode = nowNode.next;
}
}
}
void retrieve() {
Node nowNode = head.next;
while (nowNode.next != null) {
System.out.print(nowNode.data + " -> ");
nowNode = nowNode.next;
}
System.out.println(nowNode.data);
}
}
class Reference {
int count = 0;
public Reference() {
count = 0;
}
}
public class test {
public static void main(String[] args) {
LinkedList l1 = new LinkedList();
l1.append(9);
l1.append(1);
l1.append(4);
l1.append(6);
l1.append(3);
Reference r = new Reference();
Node result = find(l1.head.next, 3, r);
System.out.println(result.data);
}
public static Node find(Node node, int k, Reference r) {
if (node == null) {
return null;
}
Node value = find(node.next, k, r);
r.count ++;
if (r.count == k) {
return node;
}
return value;
}
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.