This commit is contained in:
Sainnhe Park 2022-12-02 16:06:34 +08:00
parent 9d2a8bccfe
commit 7bc754ae03
2 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,18 @@
#ifndef S0206_REVERSE_LINKED_LIST_HPP
#define S0206_REVERSE_LINKED_LIST_HPP
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class S0206 {
public:
ListNode* reverseList1(ListNode* head);
ListNode* reverseList2(ListNode* head);
};
#endif

View File

@ -0,0 +1,37 @@
#include "s0206_reverse_linked_list.hpp"
// 双指针法
ListNode* S0206::reverseList1(ListNode* head) {
if (head == nullptr) {
return nullptr;
}
ListNode* pre = head;
ListNode* cur = head->next;
pre->next = nullptr;
ListNode* curNext;
while (cur != nullptr) {
curNext = cur->next;
cur->next = pre;
pre = cur;
cur = curNext;
}
return pre;
}
// 递归法
ListNode* S0206::reverseList2(ListNode* head) {
if (head == nullptr) {
return nullptr;
} else if (head->next == nullptr) {
return head;
}
// 翻转从第二个节点开始的链表
// 翻转完后 head->next 指向这个链表的末尾,而这个链表的末尾元素的 next
// 指向空指针
ListNode* last = reverseList2(head->next);
// 把这个链表末尾元素的 next 指向 head
head->next->next = head;
// 把 head->next 指向空指针
head->next = nullptr;
return last;
}