一个个节点按顺序串接起来,就构成了链表。显然这一个个节点是很关键的,假设我们要构造一个int类型的链表,那么一个节点中就需要包含两个元素:
一个是当前节点所保存的值,设为int value。
另一个就是指向下一个节点的指针,我们再假设这个节点类是node,那么这个指针就是 node *next
方法一:链表从尾到头输出,利用递归实现,不使用库函数直接printf输出的时候用递归比较好
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> value;
if (head != NULL)
{
value.insert(value.begin(),head->val);
if (head->next != NULL)
{
vector<int> tempVec = printListFromTailToHead(head->next);
if (tempVec.size()>0)
value.insert(value.begin(),tempVec.begin(),tempVec.end());
}
}
return value;
}
};
方法二:用库函数,每次扫描一个节点,将该结点数据存入vector中,如果该节点有下一节点,将下一节点数据直接插入vector最前面,直至遍历完。或者直接加在最后,最后调用reverse
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> value;
if (head != NULL)
{
value.insert(value.begin(),head->val);
while (head->next != NULL)
{
value.insert(value.begin(),head->next->val);
head=head->next;
}
}
return value;
}
};
第二种更好理解
就是依次将链表的值插在vector的最前面,然后输出vector即可
如链表:1 2 3 4 5
插入过程为
1
21
321
4321
54321