LeetCode《图解算法数据结构》链表:图书整理 I
题目
书店店员有一张链表形式的书单,每个节点代表一本书,节点中的值表示书的编号。为更方便整理书架,店员需要将书单倒过来排列,就可以从最后一本书开始整理,逐一将书放回到书架上。请倒序返回这个书单链表。
输入
head = [3,6,4,1]
输出
[1,4,6,3]
解法 1:递归
class Solution {
public:
std::vector<int> reverseBookList(ListNode* head) {
recur(head);
return res;
}
private:
std::vector<int> res;
void recur(ListNode* head) {
if (head == nullptr) return;
recur(head->next);
res.push_back(head->val);
}
};
解法 2:辅助栈法
class Solution {
public:
std::vector<int> getResultList(ListNode* head) {
std::stack<int> stk;
std::vector<int> res;
while(head!=nullptr) {
stk.push(head->val);
head = head->next;
}
while(!stk.empty()) {
res.push_back(stk.top());
stk.pop();
}
return res;
}
};
完整代码
#include <iostream>
#include <vector>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
std::vector<int> reverseBookList(ListNode* head) {
recur(head);
return res;
}
private:
std::vector<int> res;
void recur(ListNode* head) {
if (head == nullptr) return;
recur(head->next);
res.push_back(head->val);
}
};
void test() {
ListNode* head = new ListNode(1);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(3);
ListNode* n4 = new ListNode(4);
ListNode* n5 = new ListNode(5);
head->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
Solution solution;
std::vector<int> reversedList = solution.reverseBookList(head);
std::cout << "Result: " << std::endl;
for (int num : reversedList) {
std::cout << num << " ";
}
std::cout << std::endl;
}
int main() {
test();
return 0;
}
#include <iostream>
#include <vector>
#include <stack>
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
std::vector<int> getResultList(ListNode* head) {
std::stack<int> stk;
std::vector<int> res;
while(head!=nullptr) {
stk.push(head->val);
head = head->next;
}
while(!stk.empty()) {
res.push_back(stk.top());
stk.pop();
}
return res;
}
};
void test() {
ListNode* head = new ListNode(1);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(3);
ListNode* n4 = new ListNode(4);
ListNode* n5 = new ListNode(5);
head->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
Solution solution;
std::vector<int> testList = solution.getResultList(head);
std::cout << "Result: " << std::endl;
for (int x : testList) {
std::cout << x << " ";
}
std::cout << std::endl;
}
int main() {
test();
return 0;
}