-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeMap.java
71 lines (63 loc) · 1.39 KB
/
NodeMap.java
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
package java_generic;
import java.util.function.Function;
/**
* Node Map and Travers
*
* @author ÌÆÁú
*
*/
public class NodeMap {
public static void main(String[] args) {
// Map Function
Function<Integer, Integer> f = (Integer x)->(2*x);
// Initialize Node
Node<Integer> head = new Node<Integer>(1);//Head Node
Node<Integer> node = head;
for(int i=2;i<=10;i++){
node.next = new Node<Integer>(i);
node = node.next;
}
System.out.println("\n------Before Changed------");
view(head);
// Map Node
System.out.println("\n------After Changed------");
Node<Integer> h = map(head,f);
view(h);
}
/**Node Map*/
@SuppressWarnings("unchecked")
static <T, R> Node<R> map(Node<T> head, Function<T, R> f) {
if(head == null){
return null;
}
Node<R> node = new Node<R>(f.apply((T) head.data));
Node<R> h = node;
while((head=head.next) != null){
node.next = new Node<R>(f.apply((T) head.data));
node = node.next;
}
return h;
}
/**Traverse Nodes*/
static void view(Node<?> node){
while(node != null){
System.out.print(node.data);
node = node.next;
if(node != null) {
System.out.print("->");
}
}
}
}
/**Node*/
class Node<T> {
public Object data;
public Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
Node(T data) {
this(data, null);
}
}