从尾到头打印链表
题目:输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
以下使用C++的方法来实现:
- 方法一:遍历链表从尾到头依次输出
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> arr;
ListNode* pCur = head;
ListNode* pTail = NULL;
while(head != pTail)
{
pCur = head;
while (pCur->next != pTail)
{
pCur = pCur->next;
}
arr.push_back(pCur->val);
pTail = pCur;
}
return arr;
}
};
- 方法二:遍历链表,从头到尾输出,最后利用vector中的反向迭代器创建临时对象。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> arr;
ListNode* pCur = head;
while(pCur)
{
arr.push_back(pCur->val);
pCur = pCur->next;
}
return vector<int>(arr.rbegin(),arr.rend()); //反向迭代器创建临时对象
}
};
本文介绍了一种在C++中实现链表逆序打印的方法,包括两种策略:一是通过遍历链表并从尾到头输出,二是先正向遍历再利用vector的反向迭代器逆序输出。
&spm=1001.2101.3001.5002&articleId=84962510&d=1&t=3&u=5310b0eb44f145fa8ef01bae4edebea4)
744

被折叠的 条评论
为什么被折叠?



