-
Notifications
You must be signed in to change notification settings - Fork 522
/
Copy pathListReverse.java
120 lines (99 loc) · 2.09 KB
/
ListReverse.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package class009;
// 按值传递、按引用传递
// 从堆栈角度解释链表节点
// 以堆栈视角来看链表反转
public class ListReverse {
public static void main(String[] args) {
// int、long、byte、short
// char、float、double、boolean
// 还有String
// 都是按值传递
int a = 10;
f(a);
System.out.println(a);
// 其他类型按引用传递
// 比如下面的Number是自定义的类
Number b = new Number(5);
g1(b);
System.out.println(b.val);
g2(b);
System.out.println(b.val);
// 比如下面的一维数组
int[] c = { 1, 2, 3, 4 };
g3(c);
System.out.println(c[0]);
g4(c);
System.out.println(c[0]);
}
public static void f(int a) {
a = 0;
}
public static class Number {
public int val;
public Number(int v) {
val = v;
}
}
public static void g1(Number b) {
b = null;
}
public static void g2(Number b) {
b.val = 6;
}
public static void g3(int[] c) {
c = null;
}
public static void g4(int[] c) {
c[0] = 100;
}
// 单链表节点
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
// 反转单链表测试链接 : https://leetcode.cn/problems/reverse-linked-list/
class Solution {
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
// 双链表节点
public static class DoubleListNode {
public int value;
public DoubleListNode last;
public DoubleListNode next;
public DoubleListNode(int v) {
value = v;
}
}
// 反转双链表
// 没有找到测试链接
// 如下方法是对的
public static DoubleListNode reverseDoubleList(DoubleListNode head) {
DoubleListNode pre = null;
DoubleListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
}