-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
64 lines (56 loc) · 1.63 KB
/
Copy pathReverseLinkedList.java
File metadata and controls
64 lines (56 loc) · 1.63 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
62
63
64
// Source : https://leetcode.com/problems/reverse-linked-list/
// Author : cornprincess
// Date : 2020-03-10
/*****************************************************************************************************
*
* 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?
******************************************************************************************************/
package ReverseLinkedList;
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode pre = null;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = pre;
pre = curr;
curr = nextTemp;
}
return pre;
}
// TODO recursion
public ListNode reverseListRecursion(ListNode head) {
if (head == null) {
return head;
}
ListNode newHead = recursion(head);
head.next = null;
return newHead;
}
public ListNode recursion(ListNode p) {
if (p.next == null) {
return p;
} else {
ListNode next = p.next;
ListNode newHead = recursion(next);
next.next = p;
return newHead;
}
}
public ListNode recursive(ListNode head) {
if (head == null || head.next == null) return head;
ListNode p = recursive(head.next);
head.next.next = head;
head.next = null;
return p;
}
}