思路:
方法一:迭代。
创建第二个链表,第一个链表从头掉下来的节点从头插到第二个链表中。
时间复杂度O(N),空间复杂度O(N)。
/**
* 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 == nullptr || head->next == nullptr) return head;
ListNode *second = new ListNode(-1);
ListNode *head_tmp = head;
while(head != nullptr) {
ListNode *node = new ListNode(head->val);
node->next = second->next;
second->next = node;
head = head->next;
delete(head_tmp);
head_tmp = head;
}
head = second->next;
return head;
}
};
方法二:迭代。
直接在原链表上onepass。
时间复杂度O(N),空间复杂度O(1)。要比方法一效率高。
/**
* 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 == nullptr || head->next == nullptr) return head;
else {
ListNode *pre = head;
ListNode *cur = pre->next;
pre->next = nullptr;
ListNode *post = cur->next;
while(post != nullptr) {
cur->next = pre;
pre = cur;
cur = post;
post = post->next;
}
cur->next = pre;
return cur;
}
}
};
方法三:递归。
从头结点开始不断向下递归,到达尾节点后反转,然后回到上一层,继续。如果节点个数N过大,递归层次会很深。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *reverse(ListNode *head) {
if(head->next == nullptr) {
return head;
}else {
ListNode *tail = reverse(head->next);
tail->next = head;
tail = tail->next;
tail->next = nullptr;
return tail;
}
}
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) {
return head;
}
ListNode *newhead = head;
while(newhead->next != nullptr) {
newhead = newhead->next;
}
reverse(head);
return newhead;
}
};
本文详细介绍了链表反转的三种方法:迭代法、递归法和原地反转法,包括时间复杂度、空间复杂度及代码实现。
548

被折叠的 条评论
为什么被折叠?



