-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
65 lines (54 loc) · 1.42 KB
/
Copy pathReverseLinkedList.java
File metadata and controls
65 lines (54 loc) · 1.42 KB
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
package algorithm.note;
/**
* @author: mayuan
* @desc: 反转单链表
* @date: 2018/09/04
*/
public class ReverseLinkedList {
public static void main(String[] args) {
Node node3 = new Node(3, null);
Node node2 = new Node(2, node3);
Node node1 = new Node(1, node2);
Node node0 = new Node(0, node1);
printLinkedList(node0);
System.out.println();
reverseLinkedList(node0);
printLinkedList(node3);
System.out.println();
}
public static void reverseLinkedList(Node head) {
if (null == head) {
return;
}
Node preNode = null;
Node currentNode = head;
Node nextNode = currentNode.next;
while (null != currentNode) {
currentNode.next = preNode;
preNode = currentNode;
currentNode = nextNode;
if (null != currentNode) {
nextNode = currentNode.next;
}
}
}
public static void printLinkedList(Node node) {
Node cur = node;
while (null != cur) {
System.out.print(cur.value + " ");
cur = cur.next;
}
}
static class Node {
int value;
Node next;
Node(int v, Node n) {
this.value = v;
this.next = n;
}
@Override
public String toString() {
return this.value + " ";
}
}
}