-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-206-Reverse-Linked-List.java
More file actions
70 lines (53 loc) · 1.48 KB
/
LeetCode-206-Reverse-Linked-List.java
File metadata and controls
70 lines (53 loc) · 1.48 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
65
66
67
68
69
70
/*
LeetCode: https://leetcode.com/problems/reverse-linked-list/
LintCode:
JiuZhang:
ProgramCreek:
Analysis:
1.Iterative
2.Recursive
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
// 1.Iterative
// public ListNode reverseList(ListNode head) {
// if(head == null || head.next == null) return head;
// ListNode dummy = new ListNode(0);
// dummy.next = null;
// while(head != null){
// ListNode next = head.next;
// head.next = dummy.next;
// dummy.next = head;
// head = next;
// }
// return dummy.next;
// }
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 2.Recursive
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode next = head.next;
head.next = null;
ListNode newHead = reverseList(next);
next.next = head;
return newHead;
}
}