题目: 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来打印出每个节点的值.
链表节点定义如下:
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
}
解析:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
if(head == NULL){
return result;
}
ListNode *pNode = head;
while(pNode != nullptr){
result.push_back(pNode->val);
pNode = pNode -> next;
}
reverse(result.begin(), result.end());
return result;
}
};