Task
Reverse a singly linked list.
Example
1
2
|
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?
Solution
- 定义三个指针prev、curr、next,依次修改
- 每次迭代完成后,链表分为两部分,左侧的头部是prev,右侧的头部是curr和next
- 最终结束时curr和next指向原来的空指针,prev指向翻转后的链表
时间复杂度
:只遍历一次,O(n)
空间复杂度
:只用了3个指针,O(1)
- 实现:
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
|
// Runtime: 4 ms, faster than 97.48% of C++ online submissions for Reverse Linked List.
// Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Reverse Linked List.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//处理空链表
if(!head) return head;
//定义三个指针
ListNode *prev=nullptr,*curr=head,*next=head->next;
while(curr){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
}
};
|