/**
* 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;
// ListNode* P = head;
if(head != NULL)
{
result.insert(result.begin(),head->val);
while(head->next != NULL)
{
head = head->next;
result.insert(result.begin(),head->val);
}
}
return result;
}
};
思路:本来我觉得单纯的C语言中链表来做的话还是有点繁琐的,但是和vector合作起来写的话就非常简单。 我们一般用push_back()这个函数比较多,但是别忘了还有insert()这个函数,这个函数比较好的一点就在于他可以选择插入的位置,然后按照正常的遍历就可以了。
还有注意while函数里面的顺序:如果先打印的话,打印的东西就变成了head->next->val;
while(head->next != NULL)
{
result.insert(result.begin(),head->next->val);
head = head->next;
}