-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0206.java
More file actions
45 lines (40 loc) · 1.22 KB
/
_0206.java
File metadata and controls
45 lines (40 loc) · 1.22 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
package com.github.aditya;
public class _0206 {
// ITERATIVE approach - 0 ms, faster than 100.00%
// O(n) time complexity, O(1) space complexity
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
// RECURSIVE APPROACH - 0 ms, faster than 100.00%
// O(n) time complexity
class Solution_1 {
public ListNode reverseList(ListNode head) {
return reverse(head, null);
}
private ListNode reverse(ListNode head, ListNode newHead) {
if (head == null) {
return newHead;
}
ListNode next = head.next;
head.next = newHead;
return reverse(next, head);
}
}
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
}