输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
算法思路:遍历链表,用vector<int>容器盛放,使用reverse()函数反转vector
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class listoper
{
public:
typedef struct mylist
{
struct mylist *next;
int data;
}mylist;
static vector<int> list_show(mylist *head)
{
vector<int> array;
if (head->next == NULL)
{
cout << "this is a null list" << endl;
return array;
}
else
{
mylist *ptr = head->next;
while (1)
{
if (ptr == NULL)
break;
array.push_back(ptr->data);
ptr = ptr->next;
}
}
reverse(array.begin(), array.end());
return array;
}
static mylist * list_init()
{
mylist *head = new mylist;
head->next = NULL;
return head;
}
//尾插
static void list_add_tail(mylist *head,int num)
{
mylist *new_node = new mylist;
new_node->next = NULL;
new_node->data = num;
if(head->next == NULL)
{
head->next = new_node;
}
else
{
mylist *ptr = head->next;
while (1)
{
if (ptr->next == NULL)
break;
ptr = ptr->next;
}
ptr->next = new_node;
}
}
};
int main()
{
listoper::mylist *head = listoper::list_init();
for(int i = 0;i < 10;i++)
listoper::list_add_tail(head, i);
vector<int> array = listoper::list_show(head);
for (int i = 0; i < 10; i++)
cout << array.at(i) << endl;
}