链表反转

hoxiansen

反转链表需要3个本地变量

  1. pre :指向前一个节点
  2. t :当前节点
  3. next:后一个节点

反转步骤

1
2
3
4
class Node {
int value;
Node next;
}

1、初始化变量

1
2
3
Node pre = null;
Node t = head;
Node next = null;

2、循环反转

1
2
3
4
5
6
while(t!=null){
next = t.next;
t.next = pre;
pre = t;
t = next;
}


完整代码

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
import java.util.StringJoiner;

public class ReverseLinkedList {
public static void main(String[] args) {
Node node = prepareNodeList();
printNodeList(node);
Node pre = null, t = node, next;
while (t != null) {
next = t.next;
t.next = pre;
pre = t;
t = next;
}
printNodeList(pre);
}

static Node prepareNodeList() {
int[] arr = new int[]{2, 4, 5, 6, 7, 8, 9};
Node head = new Node(-1);
Node t = head;
for (int i : arr) {
Node node = new Node(i);
t.next = node;
t = node;
}
return head.next;
}

static void printNodeList(Node node) {
StringJoiner sj = new StringJoiner("-->");
while (node != null) {
sj.add(String.valueOf(node.x));
node = node.next;
}
System.out.println(sj);
}

static class Node {
int x;
Node next;

Node(int x) {
this.x = x;
}
}
}
  • 标题: 链表反转
  • 作者: hoxiansen
  • 创建于: 2023-03-03 09:49:50
  • 更新于: 2023-06-15 11:00:59
  • 链接: https://hoxiansen.top/2023/03/03/链表反转/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论