剑指offer——面试题5:从尾到头打印链表

时间:2022-02-23 19:31:24

剑指offer——面试题5:从尾到头打印链表

/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/

class Solution {//把链表节点的值从尾到头存到vector中
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if(head == NULL) return res;
ListNode* ptr=head;
while(ptr != NULL){
res.push_back(ptr->val);
ptr=ptr->next;
}
int i=0,temp=0,n=res.size(),j=n-1;
while(i<=j){
temp=res[i];
res[i]=res[n-1-i];
res[n-1-i]=temp;
i++;
j--;
}
return res;
}
};