8、逆序输出链表。
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
示例1
输入:
{1,2,3}
返回值:
[3,2,1]
示例2
输入:
{67,0,24,58}
返回值:
[58,24,0,67]
实现方法
#include <iostream>
#include <vector>
using namespace std;
struct LinkList{
int tip;
LinkList *next;
};
LinkList *CreateList();
LinkList *CreateList() {
int Input;
LinkList* head, * nodetemp, * node;
head = nullptr;
nodetemp = nullptr;
while (cin >> Input)
{
char ch;
node = new LinkList;
node->tip = Input;
if(head == nullptr){
head = node;
}else {
nodetemp->next = node;
}
nodetemp = node;
nodetemp->next = nullptr;
if((ch = cin.get()) == '\n') break;
}
cin.clear();
cin.ignore();
return head;
}
int main() {
LinkList *L = CreateList();
LinkList *cur = L;
int n = 0;
while(cur) {
n++;
cur = cur->next;
}
vector<int> a[n];
cur = L;
int i=0;
while(cur) {
a[i++] = cur->tip;
cur = cur->next;
}
for(int i=n; i>=0;i--){
cout << a[i] << ' ';
}
return 0;
}