-
Notifications
You must be signed in to change notification settings - Fork 0
206_ReverseLinkedList
a920604a edited this page Apr 14, 2023
·
1 revision
title: 206. Reverse Linked List
reverse linked list
需要三個個指標
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *pre = nullptr, *cur = head, *post = head->next;
while(post){
cur->next = pre;
pre = cur;
cur = post ;
post = post->next;
}
cur->next = pre;
return cur;
}
};
- another version
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *pre = nullptr, *cur = head;
while(cur->next){
ListNode *post = cur->next;
cur->next = pre;
pre = cur;
cur = post ;
}
cur->next = pre;
return cur;
}
};
- other version
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *pre = new ListNode(-1), *cur = head;
pre->next = head;
while(cur->next){
ListNode *post = cur->next;
cur->next = post->next;
post->next = pre->next;
pre->next = post;
}
return pre->next;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return nullptr;
if(!head->next) return head;
ListNode *node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;;
return node;
}
};
- time complexity
O(n)
- solution complexity
O(n)
footer