-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0206ReverseLinkedList.java
More file actions
61 lines (50 loc) · 1.33 KB
/
_0206ReverseLinkedList.java
File metadata and controls
61 lines (50 loc) · 1.33 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.heatwave.leetcode.problems;
/**
* 206. Reverse Linked List
* <p>
* Reverse a singly linked list.
* <p>
* Example:
* <p>
* Input: 1->2->3->4->5->NULL
* Output: 5->4->3->2->1->NULL
* Follow up:
* <p>
* A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
public class _0206ReverseLinkedList {
private static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
static class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode left = null, middle = head, right = head.next;
while (right != null) {
middle.next = left;
left = middle;
middle = right;
right = right.next;
}
middle.next = left;
return middle;
}
}
static class SolutionRecursive {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
}