-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode00206.java
73 lines (63 loc) · 1.68 KB
/
Leetcode00206.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
/**
* 206. Reverse Linked List
*
* @link https://leetcode.com/problems/reverse-linked-list
* @author vutiendat3601
* @date 2024-07-22
*/
public class Leetcode00206 {
public ListNode reverseList(ListNode head) {
return reverseLinkedList(head, null);
}
private ListNode reverseLinkedList(ListNode head, ListNode tail) {
if (head == null) {
return tail;
}
ListNode nextHead = head.next;
head.next = tail;
return reverseLinkedList(nextHead, head);
}
public static void main(String[] args) {
final ListNode head = ListNode.from(1, 2, 3, 4);
final Leetcode00206 leetcode00206 = new Leetcode00206();
final ListNode result = leetcode00206.reverseList(head);
ListNode.print(result);
}
static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override
public String toString() {
return String.valueOf(val);
}
public static ListNode from(int... nums) {
final ListNode beforeHead = new ListNode();
if (nums != null && nums.length > 0) {
beforeHead.next = new ListNode(nums[0]);
ListNode head = beforeHead.next;
for (int i = 1; i < nums.length; i++) {
head.next = new ListNode(nums[i]);
head = head.next;
}
}
return beforeHead.next;
}
public static void print(ListNode head) {
if (head != null) {
while (head.next != null) {
System.out.print(head.val + "->");
head = head.next;
}
System.out.println(head.val);
}
}
}
}