书店店员有一张链表形式的书单,每个节点代表一本书,节点中的值表示书的编号。为更方便整理书架,店员需要将书单倒过来排列,就可以从最后一本书开始整理,逐一将书放回到书架上。请倒序返回这个书单链表。
示例 1:
**输入:**head = [3,6,4,1]
输出:[1,4,6,3]
提示:
0 <= 链表长度 <= 10000
可以反转链表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: vector<int> reverseBookList(ListNode *head) { if (head == nullptr) return {}; ListNode *pre = nullptr, *cur = head; while (cur != nullptr) { ListNode *ne = cur->next; cur->next = pre; pre = cur; cur = ne; } vector<int> ans; for (ListNode *i = pre; i != nullptr; i = i->next) { ans.push_back(i->val); } return ans; } };
|
也可以先将链表元素入栈,再取出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: vector<int> reverseBookList(ListNode *head) { stack<int> mid; vector<int> ans; for (ListNode *i = head; i != nullptr; i = i->next) { mid.push(i->val); } while (!mid.empty()) { ans.push_back(mid.top()); mid.pop(); } return ans; } };
|