-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoffer24.java
More file actions
52 lines (50 loc) · 1.34 KB
/
offer24.java
File metadata and controls
52 lines (50 loc) · 1.34 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
/**
* [24] 反转链表
*
* 题目: 输入一个链表的头节点, 反转该链表并输出反转后链表的头节点.
*
* 思路: 反转链表, 1. 迭代.
* 2. 递归.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
/**
* 时间复杂度: O(n)
* 空间复杂度: O(1)
*/
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
// when reverse current listNode's next point,
// use succ to storage current listNode's next listNode,
// in case break list.
ListNode pre = null, cur = head, succ = null;
while (cur != null) {
succ = cur.next;
cur.next = pre;
pre = cur;
cur = succ;
}
return pre;
}
/**
* 时间复杂度: O(n)
* 空间复杂度: O(n)
*/
public ListNode reverseList2(ListNode head) {
if (head == null || head.next == null) return head;
ListNode succ = head.next;
// recursive call reverseList2 to solve rest list,
// then reverse current head node.
ListNode newHead = reverseList2(succ);
succ.next = head;
head.next = null;
return newHead;
}
}