-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseList.java
More file actions
47 lines (36 loc) · 1.11 KB
/
Copy pathReverseList.java
File metadata and controls
47 lines (36 loc) · 1.11 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
package org.example;
public class ReverseList {
public static ListNode reverseList(ListNode head) {
// input check, null
if (head == null) {
return null;
}
// from left to right
ListNode dummy = new ListNode();
dummy.next = null;
ListNode curr = head;
while (curr != null) {
ListNode temp = curr.next;
curr.next = dummy.next;
dummy.next = curr;
curr = temp;
}
return dummy.next;
}
public static void main(String[] args) {
System.out.println("hello,world");
// 初始化链表 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1,
new ListNode(2,
new ListNode(3,
new ListNode(4,
new ListNode(5)))));
head = ReverseList.reverseList(head);
// 遍历链表
ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
}
}