【done】剑指offer——面试题5:从尾到头打印链表

力扣,https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/description/
迭代也很简单,最佳方案还是递归

class Solution {
    public int[] reverseBookList(ListNode head) {
        List<Integer> resList = new ArrayList<>();
        recur(head, resList);
        int[] resArray = new int[resList.size()];
        for (int i = 0; i < resList.size(); ++i) {
            resArray[i] = resList.get(i);
        }
        return resArray;
    }

    public void recur(ListNode head, List<Integer> resList) {
        if (head == null) {
            return;
        }
        recur(head.next, resList);
        resList.add(head.val);
    }
}

Solution1:我的答案

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {//把链表节点的值从尾到头存到vector中
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        if(head == NULL) return res;
        ListNode* ptr=head;
        while(ptr != NULL){
            res.push_back(ptr->val);
            ptr=ptr->next;
        }
        int i=0,temp=0,n=res.size(),j=n-1;
        while(i<=j){
            temp=res[i];
            res[i]=res[n-1-i];
            res[n-1-i]=temp;
            i++;
            j--;
        }
        return res;
    }
};

Solution2:20180829重做

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        if (!head) return {};//特例
        vector<int> res;
        struct ListNode *cur = head;
        while (cur) {
            res.push_back(cur->val);
            cur = cur->next;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值