题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
AC代码
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
typedef struct ListNode
{
int values;
struct ListNode *next;
} ListNode, *L;
void ListInsert(L &node)
{
L p = node;
L q = new ListNode; //q为要插入的节点
q->next = NULL; //
cin >> q->values;
while (p->next != NULL)
{
p = p->next;
}
q->next = p->next;
p->next = q;
}
void print(L node)
{
while (node != NULL)
{
cout << node->values << endl;
node = node->next;
}
}
class Solution
{
public:
vector<int> printListFromTailToHead(ListNode *head)
{
vector<int> result;
stack<int> s;
if (head == NULL)
return result;
while (head != NULL)
{
s.push(head->values);
head = head->next;
}
while (!s.empty())
{
// cout << s.top();
result.push_back(s.top());
s.pop();
}
return result;
}
//使用递归实现
void fun(L node)
{
if (node != NULL)
{
fun(node->next);
cout << node->values << endl;
}
}
};
int main()
{
L a;
a = new ListNode;
a->next = NULL;
a->values = 99;
for (int i = 0; i < 3; i++)
{
ListInsert(a);
}
print(a);
cout << "反向输出" << endl;
Solution A;
A.fun(a);
return 0;
}
总结
- 用栈本质上都可以用递归输出
来源:CSDN
作者:chenchenxiaojian
链接:https://blog.csdn.net/weixin_42100456/article/details/103916240