算法笔记 - 单链表反转(Java)

Java实现单链表反转

单链表反转使用p、q、r三个指针配合工作,使得两个节点间的指向反向,同时用r记录剩下的链表。基本流程如下图所示:

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
public class ReverseList {

public static Node reverseList(Node head){
Node p = new Node(0);
Node q = new Node(0);
Node r = new Node(0);
p = head;
q = head.next;
p.next = null;

while(q!=null){
r = q.next;
q.next = p;
p = q;
q = r;
}
head = p;
return head;
}

public static void main(String[] args) {
int count = 9;
Node t = new Node(1);
Node x = t;
for(int i = 2; i <= count; i++){
x = (x.next = new Node(i));
}
t = reverseList(t);
while(t!=null){
System.out.print(t.val+" ");
t = t.next;
}
}
public static class Node{
int val;
Node next;
Node(int v){
val = v;
}
}
}

本文为作者kMacro原创,转载请注明来源:https://zkhdev.github.io/2017/03/20/algorithm-single-linked-inversion/