-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path206_reverse_linked_list.java
More file actions
44 lines (35 loc) · 902 Bytes
/
206_reverse_linked_list.java
File metadata and controls
44 lines (35 loc) · 902 Bytes
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
/*
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ListNode new_head;
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
new_head = null;
reverseListRecursive(head).next = null;
return new_head;
}
private ListNode reverseListRecursive(ListNode node) {
if (node.next == null) {
new_head = node;
return node;
}
reverseListRecursive(node.next).next = node;
return node;
}
}