剑指offer-3 从尾到头打印链表
/**
* ?struct ListNode {
* ? ? ? ?int val;
* ? ? ? ?struct ListNode *next;
* ? ? ? ?ListNode(int x) :
* ? ? ? ? ? ? ?val(x), next(NULL) {
* ? ? ? ?}
* ?};
*/
方法一(借助棧的思想,利用容器vector):
class Solution {
public:
? ? vector<int> printListFromTailToHead(ListNode* head) {
? ? ? ? vector<int> result,result1;
? ? ? ? if(head==NULL)
? ? ? ? ? ? return result;
? ? ? ? int i=0;
? ? ? ? while(head!=NULL)
? ? ? ? {
? ? ? ? ? ? result.push_back(head->val);
? ? ? ? ? ? head=head->next;
? ? ? ? ? ? i++;
? ? ? ? }
? ? ? ? for(int j=i-1;j>=0;--j)
? ? ? ? {
? ? ? ? ? ? result1.push_back(result[j]);
? ? ? ? }
? ? ? ??
? ? ? ? return result1;
? ? }
};
?
方法二(遞歸,遞歸就是利用了棧的思想):
class Solution {
public:
? ? vector<int> result;
? ? vector<int> printListFromTailToHead(ListNode* head) {
? ? ? ? if(head!=NULL)
? ? ? ? {
? ? ? ? ? ? printListFromTailToHead(head->next);
? ? ? ? ? ? result.push_back(head->val);
? ? ? ? }
? ? ? ? return result;
? ? }
};
總結
以上是生活随笔為你收集整理的剑指offer-3 从尾到头打印链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查找和为定值的两个数—Leetcode1
- 下一篇: 硬件中断与软件中断