输入一个链表,从尾到头打印链表每个节点的值。
#include <iostream>
#include <vector>
using namespace std;
#define MAX_NUMBER 10
struct ListNode{
int val;
struct ListNode *next;
};
vector<int> printListFromTailToHead(struct ListNode* head) {
vector<int> array;
if (head != NULL)
{
if (head->next != NULL)
{
array = printListFromTailToHead(head->next);
}
array.push_back(head->val);
}
return array;
}
ListNode *CreateList()
{
ListNode *head, *s, *r;
head = new ListNode;//h为头结点
head->val = MAX_NUMBER;
r = head;
for (int i = 0; i < MAX_NUMBER; i++)
{
s = new ListNode;
s->val = i;
r->next = s;
r = s;
}
r->next ='\0';
return head;
}
int main()
{
ListNode *head = NULL;
head = CreateList();
if (head == NULL)
{
cout << "error!" << endl;
return -1;
}
vector<int> Array = printListFromTailToHead(head);
vector<int>::iterator iter;
for (iter = Array.begin(); iter != Array.end(); iter++)
{
cout << *iter << " " << endl;
}
return 0;
}