用链表+vector来解:
/**
* 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) {
ListNode *reverse = new ListNode;
reverse->next = NULL;
while(head!=NULL)
{
ListNode *p = new ListNode;
p->val = head->val;
p->next = reverse->next;
reverse->next = p;
head = head->next;
}
vector<int> vec;
reverse = reverse->next;
while(reverse!=NULL)
{
vec.push_back(reverse->val);
reverse = reverse->next;
}
return vec;
}
};
用栈+vector来解
/**
* 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> m_st;
while(head!=NULL)
{
m_st.push(head->val);
head=head->next;
}
vector<int> vec;
while(!m_st.empty())
{
vec.push_back(m_st.top());
m_st.pop();
}
return vec;
}
};