-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathReverseNode.java
51 lines (41 loc) · 1.09 KB
/
ReverseNode.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
package algorithm;
public class ReverseNode {
static class Node {
Node next;
int value;
public Node(Node next, int value) {
this.next = next;
this.value = value;
}
}
public static Node reverse(Node head) {
if (head == null) {
return null;
}
Node result = new Node(null, 0);
Node cur = head;
while (cur != null) {
Node temp = cur;
cur = cur.next;
temp.next = result.next;
result.next = temp;
}
return result.next;
}
public static void main(String[] args) {
Node node1 = new Node(null, 1);
Node node2 = new Node(node1, 2);
Node node3 = new Node(node2, 3);
Node node4 = new Node(node3, 4);
Node node5 = new Node(node4, 5);
print(node5);
print(reverse(node5));
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.value + "\t");
head = head.next;
}
System.out.println();
}
}