s0206
This commit is contained in:
parent
9d2a8bccfe
commit
7bc754ae03
18
include/s0206_reverse_linked_list.hpp
Normal file
18
include/s0206_reverse_linked_list.hpp
Normal 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
|
37
src/s0206_reverse_linked_list.cpp
Normal file
37
src/s0206_reverse_linked_list.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user