leetcode 剑指offer 6 从尾到头打印链表
作者:互联网
问题描述:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
C++4种解法:reverse反转法、堆栈法、递归法、改变链表结构法
堆栈法举例:
自我题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
const ListNode *node = head;
std::size_t count = 0;
while(node != nullptr)
{
++count;
node = node->next;
}
std::vector<int>num(count);
node = head;
for(auto it = num.rbegin(); it != num.rend(); it++)
{
*it = node->val;
node = node->next;
}
return num;
}
};
牛人题解:
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
//方法1:reverse反转法
/*
while(head){
res.push_back(head->val);
head = head->next;
}
//使用algorithm算法中的reverse反转res
reverse(res.begin(),res.end());
return res;
*/
//方法2:入栈法
/*
stack<int> s;
//入栈
while(head){
s.push(head->val);
head = head->next;
}
//出栈
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
*/
//方法3:递归
/*
if(head == nullptr)
return res;
reversePrint(head->next);
res.push_back(head->val);
return res;
*/
//方法4:改变链表结构
ListNode *pre = nullptr;
ListNode *next = head;
ListNode *cur = head;
while(cur){
next = cur->next;//保存当前结点的下一个节点
cur->next = pre;//当前结点指向前一个节点,反向改变指针
pre = cur;//更新前一个节点
cur = next;//更新当前结点
}
while(pre){//上一个while循环结束后,pre指向新的链表头
res.push_back(pre->val);
pre = pre->next;
}
return res;
}
};
标签:pre,node,head,ListNode,offer,res,next,链表,从尾 来源: https://www.cnblogs.com/zeroluo/p/14170627.html