题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
#include <cstddef>
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> arr;
ListNode* cur = head;
ListNode* next = NULL;
ListNode* L = (ListNode*)malloc(sizeof(ListNode));
L -> val = -1;
L -> next = NULL;
// 逆置链表
while(cur != NULL) {
next = cur -> next;
cur -> next = L ->next;
L -> next = cur;
cur = next;
}
next = L;
while(next -> next != NULL) {
next = next -> next;
arr.push_back(next -> val);
}
return arr;
}
};
三奇智元机器人科技有限公司公司福利 74人发布