-
Notifications
You must be signed in to change notification settings - Fork 10
/
ReverseLinkList.java
39 lines (31 loc) · 1.06 KB
/
ReverseLinkList.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
package com.camnter.basicexercises.linklist;
import com.camnter.basicexercises.core.Node;
/**
* 反转链表
*
* 记录此次循环当前节点,作为 previous
* 以备下次循环的时候指向 current.next = previous
*
* @author CaMnter
*/
public class ReverseLinkList<T> {
private Node<T> reverseLinkList(Node<T> head) {
Node<T> previous = null;
Node<T> current = head;
while (current != null) {
// 拿到下个节点
Node<T> next = current.next;
// 改变下个节点的引用,previous 用于记录上个循环中的 current
current.next = previous;
// 记录这个循环中的 current,以备下个循环用
previous = current;
// 移动引导到下个节点
current = next;
}
return previous;
}
public static void main(String args[]) {
ReverseLinkList<Integer> reverseLinkList = new ReverseLinkList<Integer>();
Node.printLinkList(reverseLinkList.reverseLinkList(Node.getLinkList()));
}
}