
链表遍历值–》放进栈里,,在一次取出来添到vector(反转一般会想到栈的特性)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
stack<int> revse;
while(head)
{
revse.push(head->val);
head=head->next;
}
while(!revse.empty())
{
res.push_back(revse.top());
revse.pop();
}
return res;
}
};
链表直接反转(双指针)之后,再遍历值填到vector后面
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
ListNode* pre=NULL;
ListNode* cur=head;
while(cur)
{
ListNode* Next=cur->next;
cur->next=pre;
pre=cur;
cur=Next;
}
while(pre)
{
res.push_back(pre->val);
pre=pre->next;//此时为空,上个是有值的
}
return res;
}
};
直接遍历链表,并且计数, 然后反向存入数组(类似例子如单词的反转,数组计数定位)
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
int count=0;
ListNode* phead=head;
while (phead)
{
phead=phead->next;
count++;
}
vector<int> res(count);
for(int i=count-1;i>=0;--i)
{
res[i]=head->val;
head=head->next;
}
return res;
}
};