LeetCode(剑指 Offer)- 06. 从尾到头打印链表

Posted 程序员牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 06. 从尾到头打印链表相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:略。

解题思路:略。

相关企业

  • 字节跳动

AC 代码

  • Java
/**
 * Definition for singly-linked list.
 * public class ListNode 
 *     int val;
 *     ListNode next;
 *     ListNode(int x)  val = x; 
 * 
 */
// 解决方案(1)
class Solution 
    public int[] reversePrint(ListNode head) 
        int i = 0;
        ListNode p = head;
        while (null != p) 
            p = p.next;
            i++;
        

        int[] arr = new int[i];
        while (null != head) 
            arr[--i] = head.val;
            head = head.next;
        

        return arr;
    


// 解决方案(2)
class Solution 
    ArrayList<Integer> tmp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) 
        recur(head);
        int[] res = new int[tmp.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = tmp.get(i);
        return res;
    
    void recur(ListNode head) 
        if(head == null) return;
        recur(head.next);
        tmp.add(head.val);
    


// 解决方案(3)
class Solution 
    public int[] reversePrint(ListNode head) 
        LinkedList<Integer> stack = new LinkedList<Integer>();
        while(head != null) 
            stack.addLast(head.val);
            head = head.next;
        
        int[] res = new int[stack.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = stack.removeLast();
    return res;
    
  • C++
// 解决方案(1)
class Solution 
public:
    vector<int> reversePrint(ListNode* head) 
        recur(head);
        return res;
    
private:
    vector<int> res;
    void recur(ListNode* head) 
        if(head == nullptr) return;
        recur(head->next);
        res.push_back(head->val);
    
;

// 解决方案(2)
class Solution 
public:
    vector<int> reversePrint(ListNode* head) 
        stack<int> stk;
        while(head != nullptr) 
            stk.push(head->val);
            head = head->next;
        
        vector<int> res;
        while(!stk.empty()) 
            res.push_back(stk.top());
            stk.pop();
        
        return res;
    
;

以上是关于LeetCode(剑指 Offer)- 06. 从尾到头打印链表的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]剑指 Offer 06. 从尾到头打印链表

[LeetCode]剑指 Offer 06. 从尾到头打印链表

LeetCode 剑指offer 面试题06. 从尾到头打印链表

LeetCode 剑指offer 面试题06. 从尾到头打印链表

刷题记录leetcode 剑指 Offer(第 2 版)03-11

Leetcode剑指 Offer 06. 从尾到头打印链表(辅助栈)