使用栈类型 先入后出 时间 30-80不等 空间 100
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> sta;
ListNode* tmp=head;
vector<int> result;
while(tmp!=NULL)
{
sta.push(tmp->val);
tmp=tmp->next;
}
while(!sta.empty())
{
int tmpvalue=sta.top();
result.push_back(tmpvalue);
sta.pop();
}
return result;
}
};
链表逆序 复杂度和上面一样
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> result;
if(head==NULL)
{return result;}
ListNode* cur=head;
ListNode* pre=NULL;
ListNode* tmp=NULL;
while(cur!=NULL)
{
tmp=cur->next;
cur->next=pre;
pre=cur;
cur=pre;
}
while(pre!=NULL)
{
result.push_back(pre->val);
pre=pre->next;
}
return result;
}
};