1、递归
每读入一个新元素后新建一个节点并指向逆序后的上一个节点。由于需要额外n个节点,空间复杂度高。
class Solution {
public:
ListNode *reverse(ListNode *next, ListNode *reversed_first) {
if (next == nullptr) {
return reversed_first;
}
ListNode *temp = new ListNode(next->val, reversed_first);
return reverse(next->next, temp);
}
ListNode *reverseList(ListNode *head) {
if (!head) return head;
ListNode *temp = new ListNode(head->val);
return reverse(head->next, temp);
}
};
2、递归(原地)
我们利用former记录已经逆序的节点,每读入一个新节点时,我们保存他的下一个节点,并将它的next指针指向先前已经排好序的节点,如此重复直至遍历完链表,最后返回已经排好序的节点。
class Solution {
public:
ListNode *former = NULL;
ListNode *reverseList(ListNode *head) {
if (!head) return former;
ListNode *temp = head->next;
head->next = former;
former = head;
return reverseList(temp);
}
};
3、迭代(原地)
我们遍历链表中的每一个节点,为了让链表逆序,我们需要让当前节点的下一个节点的next指针指向自己,而自己的next指针指向前一个逆序完成的节点。而后我们让当前节点成为新的完成的逆序节点,并移动到下一个节点。
class Solution {
public:
ListNode *reverseList(ListNode *head) {
if (!head || head->next == nullptr) return head;
ListNode *cur = head;
ListNode *former = NULL;
while (cur->next != nullptr) {
ListNode *temp = cur->next;
cur->next = former;
former = cur;
cur = temp;
}
cur->next = former;
return cur;
}
};
或
class Solution {
public:
ListNode *reverseList(ListNode *head) {
if (!head || head->next == nullptr) return head;
ListNode *cur = head;
ListNode *former = NULL;
while (cur) {
ListNode *temp = cur->next;
cur->next = former;
former = cur;
cur = temp;
}
return former;
}
};