题目描述
输入一个链表,从尾到头打印链表每个节点的值。
代码如下:(主要是存储每个节点的指针值)
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> listVal;
if (head != NULL)
listVal.push_back(head->val);
else
return listVal;
while (head->next != NULL){
head = head->next;
listVal.push_back(head->val);
}
vector<int> v;
vector<int>::reverse_iterator i = listVal.rbegin();
for (; i != listVal.rend(); ++i){
v.push_back(*i);
//cout << (*i) << endl;
}
return v;
}
};
/* 测试
int main(){
ListNode* head = new ListNode(5);
ListNode* node_1 = new ListNode(6);
ListNode* node_2 = new ListNode(7);
node_1->next = head->next;
head->next = node_1;
node_2->next = node_1->next;
node_1->next = node_2;
Solution *s = new Solution();
vector<int> v(s->printListFromTailToHead(head));
vector<int>::reverse_iterator i = v.rbegin();
for (; i != v.rend(); ++i){
cout << (*i) << endl;
}
system("pause");
return 0;
}
*/