【链表专题】剑指 Offer 06. 从尾到头打印链表

本问题对应课程链接:剑指offer刷题第五期

要求:

1、请打卡你的解题代码,如果能简单说一下思路则简单说一下思路。
2、给出你代码所用的时间复杂度和空间复杂度

共以下 41 个回答

  • mpweixin用户 普通 2024年5月14日 上午11:56

    打卡成功!

    0 赞同 0 条回复
  • 刘成志 永久会员 2023年10月17日 下午7:00

    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * ListNode next;
    * ListNode() : val(0), next(nullptr) {}
    * ListNode(int x) : val(x), next(nullptr) {}
    * ListNode(int x, ListNode *next) : val(x), next(next) {}
    * };
    */
    class Solution {
    public:
    vector reverseBookList(ListNode
    head) {
    recur(head);
    return res;
    }
    private:
    std::vector res;
    void recur(ListNode* head)
    {
    if (head nullptr)
    {
    return;
    }
    recur(head->next);
    res.push_back(head->val);
    }

    };
    时空复杂度都是 O(n)

    0 赞同 0 条回复
  • 梧葳 普通 2023年8月28日 下午11:54

    判空–>计算长度–>申请堆区空间–>数组从后往前接收值–>返回。(注意:C语言解题时需将长度赋值给returnSize)
    “””
    int* reversePrint(struct ListNode* head, int* returnSize){
    // 判空
    // if (head NULL) {
    // return NULL;
    // }
    int count = 0;
    struct ListNode* tmp_list = head;
    // 计算链表长度
    while (tmp_list != NULL) {
    count++;
    tmp_list = tmp_list->next;
    }

    // 申请内存大小
    *returnSize = count;
    int len = count - 1;  
    int *arr = (int *)calloc(count, sizeof(int)); 
    
    // 将数组从后往前接收元素
    while (head != NULL) {
        arr[len--] = head->val;
        head = head->next;
    }
    
    return arr;
    

    }
    “””

    0 赞同 0 条回复
  • 我一定要坚持打卡 普通 2023年8月26日 下午9:44

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

    > Problem: 剑指 Offer 06. 从尾到头打印链表

    用数组的形式,将所给的链表倒叙打印出来

    [TOC]

    思路

    解题思路

    倒叙的打印一个链表,这里可以从两个角度去考虑,第一个是对链表进行处理,将链表的数据进行翻转,然后在正序打印【反转链表】;第二个角度是将链表数据反向的复制出来,然后正序的打印【倒叙输出:考虑栈的作用以及倒叙遍历】;

    image-20230826210754091

    ①数据先入栈,然后出栈就是倒顺序② ③先将链表进行倒叙【递归和非递归】,再讲数据正序打印 ④正序遍历使用两个数组暂存数据并倒叙输出数据 ⑤使用一个数组完成数据倒叙

    解题方法

    解题方法1

    1. 使用栈先进后出暂存数据并输出结果
    2. 这里要确定好数据的个数,方便返回对应的大小的数组
     /**
          * 使用栈 先把链表数据存入到栈中,然后将数据从栈中弹出到数组中,直接返回即可
          *    空间复杂度较低,时间复杂度较高
          * @param head
          * @return
          */
         public int[] reversePrint1(ListNode head) {
    
                Stack<Integer> Integers =new Stack<Integer>();
                if (head ==null) {
                    return new int[0];
                }
                ListNode temp= head;
                int num = 0;
                while (temp != null) {
                    Integers.add(temp.val);
                    temp= temp.next;
                    num++;
                }
                int a[]  = new int[num];
                for (int i = 0; i < num; i++) {
                    a[i]=Integers.pop();
                }
                return a;
         }
    

    时间复杂度: $O(n)$

    空间复杂度: $O(n)$

    解题方法2+3

    递归法

    递归法

    将数组倒序,然后正序的遍历数组并写入到数组中

    倒叙数组有两种方法,一种是递归的,一种是非递归的

    具体实现的话有四种实现方式

    非递归的方法:一种是使用类双指针(实际是3个指针)来将数组倒叙,从头到尾将箭头反向;另一种是使用头插法将数据重新插入一遍

    递归的有两种,一种是用递归实现3指针,类似于非递归的双指针法;另一种是直接使用子递归实现,处理好父递归和子递归之间的关系即可

    这里有个麻烦的点是在使用递归方法的时候,不能直接一次遍历查出数据的个数,需要再重新遍历一遍,并且使用递归增加了空间复杂度

     /**
          * 先将链表进行倒置,然后直接遍历进行数据写入新数组并返回【这里数组翻转可以有递归和非递归两种实现方式】
          * 递归版
          */
         public static int[] reversePrint2(ListNode head) {
             int num = 0;
             head = reverseList(head);
             ListNode temp = head;
    //       统计数量
             while (temp!=null) {
                num++;
                temp =temp.next;
             }
    
             temp =head;
             int a[]  = new int[num];
             for (int i = 0; i < num; i++) {
                 a[i] = temp.val;
                 temp=temp.next;
            }
            return a;
         }
    
         public static ListNode reverseList(ListNode head) {
            if (head==null || head.next == null) {
                return head;            
            }
    
            ListNode tempListNode = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return tempListNode;
        }
    
    

    在上边代码中没有使用递归三指针倒叙法【不要求掌握】,掌握递归的一种方法即可

    递归的空间复杂度与使用栈的空间复杂度是一致的,所以需要使用非递归的方法进行优化

    时间复杂度: $O(n)$

    空间复杂度: $O(n)$

    非递归法

    非递归法

    使用非递归法的话,就是只需要改变一下链表倒叙的算法即可,正序打印链表的方法没有改变,跟上边一样

    这里用两个指针,对链表进行倒叙的时候,老是习惯先将快指针和慢指针指向同一个地方,然后先让快指针走,这是错误的;应该在循环

    之前就让慢指针指向null,让快指针指向head,直接进入循环的时候,先改变head指针的指向,在倒叙链表中其他元素的指向

     /**
          * 先将链表进行倒置,然后直接遍历进行数据写入新数组并返回【这里数组翻转可以有递归和非递归两种实现方式】
          * 非递归版
         */
         public static int[] reversePrint3(ListNode head) {
    
             int num = 0;
             head = reverseList1(head);
             ListNode temp = head;
    //       统计数量
             while (temp!=null) {
                num++;
                temp =temp.next;
             }
    
             temp =head;
             int a[]  = new int[num];
             for (int i = 0; i < num; i++) {
                 a[i] = temp.val;
                 temp=temp.next;
            }
            return a;
         }
    
         public static ListNode reverseList1(ListNode head) {
    
             if (head==null || head.next == null) {
                 return head;
            }
    //       都从头节点开始
             ListNode temp = head;
    
             ListNode preListNode = head;// 前指针
             ListNode lastListNode = null;// 后指针
             while (preListNode != null) {
    //           preListNode =temp;// 这个地方 一开始写三指针 还是会被卡主,想着先移动前指针  但是这里有一步是没在循环中执行的
    //           在循环外让前指针比后指针快一步,先让前指针指向head,而后指针指向null,方便更改head的指向,先让head指为null
                 temp = preListNode.next;
                 preListNode.next=lastListNode;
                 lastListNode = preListNode;
                 preListNode =temp;
            }
             return lastListNode;
        } 
    
    

    时间复杂度: $O(n)$

    空间复杂度: $O(1)$

    非递归倒叙链表的方式是原地的,所以空间复杂度比较低

    解题方法4+5

    分别使用两个链表和使用一个链表对数组进行存储并倒叙的写入,正向遍历链表,然后倒叙的进行赋值设定

    使用两个数组的时候,会将数组进行复制,也就是先正序的复制到一个数组中,在倒序的将数组复制到另一个数组中,实现将数据再倒叙的赋值

    使用一个数组的时候,直接在遍历链表的时候,从后往前的写入到数组中,实现数组的数据倒叙

    注意点:

    1. 在使用数组的时候,要先弄清楚数据的个数,在申请空间
    2. 数组的下标与数据个数相差1,所以要在写入的时候,先将数据个数-1 在写入到数组中
    package day2;
    
    
    import java.util.Stack;
    
    
    
    public class 剑指Offer06从尾到头打印链表 {
    
        /**
        *    下边的第一个方法使用的是用两个数组,第一个先遍历链表存储数据,并把该数组倒序复制到另一个数组中
        *    空间复杂度较高,时间复杂度稍快.
         * @param head
         * @return
         */
         public int[] reversePrint0(ListNode head) {
                int a[]  = new int[10000];
    
    //          int[] b = new int[100];//数组的另外一种定义方式
    
                if (head==null) {
                    return new int[0];
                }
                ListNode temp = head;
    
                int i = 0;
                for (; temp != null; i++) {
                    a[i] = temp.val;
                    temp = temp.next;
                }
    //          i=0;
    //          while (temp != null) {
    //              a[i] = temp.val;
    //              i++;
    //              temp = temp.next;
    //          }
                int num = i;
                int[] b = new int[num];//数组的另外一种定义方式
                for (int j = 0; j < num; j++) {
                    b[j] = a[i-1];// 这里获取数据的时候,坐标与数据序号差1
                    i--;
                }
    
                return b;
    
            }
    
         /**
          * 对上边一个方法进行改进,不使用两个数组进行处理,直接用一个数组进行处理,在使用数组的时候进行倒叙的写入数组即可
          */
         public int[] reversePrint00(ListNode head) {
                if (head==null) {
                    return new int[0];
                }// 特殊处理
                int num = 0;// 设定长度
                ListNode tempListNode =head;
                while (tempListNode!= null) {
                    num++;
                    tempListNode= tempListNode.next;                
                }
                int a[]  = new int[num];
    
                while (head!= null) {
                    a[num-1] = head.val;
                    head= head.next;
                    num--;
                }
                return a;
         }
    
    
    
    
    
            public static void main(String[] args) {
                ListNode list  =new ListNode(0);
                ListNode list1 =new ListNode(1);
                list.next=list1;
                ListNode list2 =new ListNode(2);
                list1.next=list2;
                ListNode list3 =new ListNode(3);
                list2.next=list3;
                ListNode list4 =new ListNode(4);
                list3.next=list4;
                list4.next=null;
    
                ListNode temp =list;
                while (temp!=null) {
                    System.out.println(temp.toString());
                    temp=temp.next;
                }
                int[] a = reversePrint0(list);
                System.out.println("调整完成");
    
                for (int i = 0; i < a.length; i++) {
                    System.out.println(a[i]);
                }
            }
    
    
    
    }
    
    
    0 赞同 0 条回复
  • 黎明之前 普通 2023年8月23日 上午11:33

    //有三种方式
    //1 使用栈 2 使用反转链表 递归和原地 3 使用数组反向遍历 从右向左遍历
    //一共四种方法 前两个时间和空间复杂度都为O(n) 后面两个时间为O(n) 空间为O(1)
    if(head NULL)
    return{};
    int count=0;
    ListNode *temp =head;
    while(temp )
    {
    count++;
    temp = temp->next;
    }
    vector res(count)
    int k = count-1;
    while(head)
    {
    res[k–] = head->val;
    head= head->next;

    }
    return res;

    0 赞同 0 条回复
  • 小火 普通 2023年8月21日 下午9:20

    栈先进后出(判断栈为空:empty())
    时间复杂度:O(n) 空间复杂度:O(n)

    /**
     * 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) {
            vector<int> ans;
            stack<int> p;
            while(head!=NULL) {
                p.push(head->val);
                head=head->next;
            }
            while(!p.empty()) {
                int i = p.top();
                p.pop();
                ans.push_back(i);
            }
    
            return ans;
    
        }
    };
    
    0 赞同 0 条回复
  • Serena 普通 2023年8月20日 下午9:34

    时间O(n),空间O(1)

    class Solution {
    public int[] reversePrint(ListNode head) {
    //统计链表长度
    int length=0;
    for(ListNode l=head;l!=null;l=l.next){
    length++;
    }
    //创建数组
    int[] res=new int[length];
    //把链表数值倒序存储到数组中(链表第一个对应数组第length-1个,i->length-i)
    ListNode l=head;
    for(int i=1;i<=length;i++,l=l.next){
    res[length-i]=l.val;
    }
    return res;
    }
    }

    0 赞同 0 条回复
  • Di questa storia sempre a lie to 普通 2023年8月19日 下午4:39

    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) : val(x), next(NULL) {}
    * };
    */
    class Solution {
    public:
    vector reversePrint(ListNode
    head) {
    if(headNULL) return {};
    vectora = reversePrint(head->next);
    a.push_back(head->val);
    return a;
    }
    };
    时间复杂度:o(N)
    空间复杂度:O(1)

    0 赞同 0 条回复
  • 谁仁 普通 2023年8月17日 下午2:58

    // 递归方式打印链表
    void printListReversely(ListNode* head) {
    if (head NULL) {
    return;
    }

    printListReversely(head->next);  // 递归遍历下一个结点
    
    printf("%d ", head->val);  // 打印当前结点的值
    

    时间复杂度o(n),空间复杂度o(n)

    0 赞同 0 条回复
  • 海浪漂哇漂 普通 2023年8月16日 下午10:51

    打卡
    class Solution {
    public int[] reversePrint(ListNode head) {
    ListNode temp = head;
    int count = 0;
    while(temp != null){
    temp = temp.next;
    count++;
    }
    int[] arr = new int[count];
    int k = count – 1;
    while(head != null){
    arr[k–] = head.val;
    head = head.next;
    }
    return arr;
    }
    }

    0 赞同 0 条回复
  • mpweixin用户 普通 2023年8月16日 下午10:13

    打卡

    /**
     * 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) {
            if(head == NULL) return {};
            ListNode * cur = head;
            int count = 0;
            while(cur != NULL){
                count++;
                cur = cur->next;
            }
            vector<int> array(count);
            cur = head;
            for(int i = count - 1; i >= 0; i--){
                array[i] = cur->val;
                cur = cur->next;
            }
            return array;
        }
    };
    
    0 赞同 0 条回复
  • mpweixin用户 普通 2023年8月16日 下午8:24

    //首先通过遍历将每一个节点都塞入vector中;
    //然后再将通过reverse函数将里面的节点顺序掉换;
    //时间复杂度为o(n);
    //空间复杂度为o(n);
    class Solution {
    public:
    vector reversePrint(ListNode* head) {
    vector
    vec;
    ListNode *p=head;
    while(head){
    vec.push_back(head->val);
    head=head->next;
    }
    reverse(vec.begin(),vec.end());
    return vec;

    }
    

    };

    0 赞同 0 条回复
  • sc_Yang 普通 2023年8月16日 下午12:05

    空间复杂度:o(m),时间复杂度:o(m)

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        // 递归打印
        vector<int> newList;
        vector<int> reversePrint(ListNode* head) {
            if(head==NULL){
                return newList;
            }
            else{
                if(head->next){
                    reversePrint(head->next);
                }
                newList.push_back(head->val);
                return newList;
            }
        }
    };
    
    0 赞同 0 条回复
  • Miracle· 普通 2023年8月16日 上午10:36

    时间复杂度:o(n),空间复杂度:o(n)
    思路:创建一个栈,先遍历链表将元素压入栈中,后将栈中的元素依次弹出放入到数组中。
    class Solution {
    public:
    vector reversePrint(ListNode* head) {
    stack
    stk;
    vector
    ans;
    while (head != NULL) {
    stk.push(head->val);
    head = head->next;
    }

        while (stk.size() != 0) {
            auto x = stk.top();
            stk.pop();
    
            ans.push_back(x);
        }
    
        return ans;
    }
    

    };

    0 赞同 0 条回复
  • 💮黧大王.exe 普通 2023年8月15日 下午10:44

    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) : val(x), next(NULL) {}
    * };
    */
    class Solution {
    vector result;
    public:
    vector
    reversePrint(ListNode
    head) {
    /if(head!=NULL){
    reversePrint(head->next);
    result.push_back(head->val);
    }
    return result;
    /递归 时间复杂度O(n) 空间复杂度O(n)
    int count=0;
    ListNode *t=head;
    while(t!=NULL){
    t=t->next;
    count++;
    }
    vector res(count);
    while(head != NULL){
    res[–count] = head->val;
    head = head->next;
    }//从右往左遍历 时间复杂度O(n) 空间复杂度O(1)
    return res;
    }
    };

    0 赞同 0 条回复
  • Prime 普通 2023年8月15日 下午10:41

    递归方法时间和空间复杂度都为O(N)

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reversePrint(self, head):
            """
            :type head: ListNode
            :rtype: List[int]
            """
            res = []
            def recuse(node):
                if not node:
                    return 
                recuse(node.next)
                res.append(node.val)
            recuse(head)
            return res
    
    
    0 赞同 0 条回复
  • Delete隐身 普通 2023年8月15日 下午10:29

    思路:先统计链表长度,再定义一个等同大小的数组,遍历链表依次从后往前添加到数组中
    时间复杂度:O(n),空间复杂度:O(n)
    class Solution {
    public int[] reversePrint(ListNode head) {
    if(head null) {
    return new int[0];
    }
    ListNode cur = head;
    int length = 0;
    while(cur != null) {
    length++;
    cur = cur.next;
    }
    int[] result = new int[length];
    cur = head;
    for(int i = length – 1; i >= 0; –i) {
    result[i] = cur.val;
    cur = cur.next;
    }
    return result;
    }
    }

    0 赞同 0 条回复
  • Sheng 永久会员 2023年8月15日 下午8:39

    时间复杂度O(n^2)空间复杂度O(n^2)
    感觉函数行参给少了,多给两个形参,一个是大小,一个是初始化好的数组引用,时间空间复杂度能降到O(n)。只有一个形参代码写的很难受。
    ”’java
    //从尾头打印链表,使用递归
    public class Solution {
    public int[] reversePrint(ListNode head)
    {
    if(head null)
    return new int[0];

        ListNode node = head;
        int count = 1 ;
        while(node.next!=null)
        {
            count++;
            node = node.next;
        }
    
        int[] array = new int[count];
        int k = count - 1;
        int[] tmp = reversePrint(head.next);
        for(int j=0;j<k; j++)
        {
            array[j] = tmp[j];
        }
        array[k] = head.val;
        return array;
    }
    

    }

    0 赞同 0 条回复
  • Joel 普通 2023年8月15日 下午2:23

    时间O(n) 空间O(n)

    class Solution:
        def reversePrint(self, head: ListNode) -> List[int]:
            if head == None:
                return []
            # val = []
            # while head != None:
            #     val.append(head.val)
            #     head = head.next
            # return val[::-1]
            if head.next == None:
                return [head.val]
            val = []
            for i in self.reversePrint(head.next):
                val.append(i)
            val.append(head.val)
            return val
    
    0 赞同 0 条回复
  • 一个人的风海吹了两遍 普通 2023年8月15日 下午1:38

    时间复杂度O(n)
    空间复杂度O(n)
    先遍历一遍链表获得长度
    再创建对应长度的数组
    遍历第二遍插入数组就行

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] reversePrint(ListNode head) {
            ListNode temp = head;
            int num = 0;
            while(temp!=null){
                num++;
                temp=temp.next;
            }
            temp = head;
            int[] re = new int[num];
            for(int i=num-1; i>=0; i--){
                re[i]=temp.val;
                temp = temp.next;
            }
            return re;
        }
    }
    
    0 赞同 0 条回复
  • mpweixin用户 永久会员 2023年8月15日 上午11:54

    ector reversePrint(ListNode* head) {
    if(head nullptr){
    return vector{};
    }
    if(head->next
    nullptr){
    vector
    tmp;
    tmp.emplace_back(head->val);
    return tmp;
    }
    递归实现
    vector
    ans = reversePrint(head->next);
    ans.emplace_back(head->val);

        return ans;
    }
    

    0 赞同 0 条回复
  • 行动派小彩笔 普通 2023年8月14日 下午11:01
     // 递归思想,从尾到头进行push_back
     // 时间链表长度O(n), 空间递归深度O(n)
    class Solution {
    public:
        vector<int> ans;
        void dfs(ListNode* head)
        {
            if(!head) return;
            dfs(head->next);
            ans.push_back(head->val);
        }
        vector<int> reversePrint(ListNode* head) {
            dfs(head);
            return ans;
        }
    };
     // 倒叙填充,时间链表长度O(n),没有额外空间开辟O(1)
    class Solution {
    public:
        vector<int> reversePrint(ListNode* head) {
            if(!head) return vector<int>{};
            ListNode *cur = head;
            int k =0;
            while(cur)
            {
                ++k;
                cur=cur->next;
            }
            vector<int> ans(k);
            cur = head;
            for(int i =k-1;i>=0;--i)
            {
                ans[i] = cur->val;
                cur = cur->next; 
            }
            return ans;
        }
    };
    
    0 赞同 0 条回复
  • 漂洋过海去见你 永久会员 2023年8月14日 下午9:10

    #python解题
    class Solution(object):
    def reversePrint(self, head):
    “””
    :type head: ListNode
    :rtype: List[int]
    “””
    if not head:
    return []

        count = 0
        cur = head
        while cur:
            count += 1
            cur = cur.next
    
        res = [0] * count
        k = count -1
        while head:
            res[k] = head.val
            k -= 1
            head = head.next
    
        return res
    
    0 赞同 0 条回复
  • 天亮之前 普通 2023年8月14日 下午9:02

    /**
    *打卡
    * Definition for singly-linked list.
    * public class ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) { val = x; }
    * }
    */
    class Solution {
    public int[] reversePrint(ListNode head) {
    if(head null)
    return new int[0];

        int count = 0;
        ListNode temp = head;
        while(temp != null) {
            count++;
            temp = temp.next;
        }
        int a[] = new int[count];
        int b = count - 1;
        while(head != null){
            a[b--] = head.val;
            head = head.next;
        }
        return a;
    }
    

    }

    0 赞同 0 条回复
  • QQiing 普通 2023年8月14日 下午8:39

    class Solution {
    vector result;
    public:
    vector
    reversePrint(ListNode* head) {
    if(head){
    reversePrint(head->next);
    result.push_back(head->val);
    }
    return result;
    }
    };
    时间复杂度O(n),空间复杂度O(1)

    0 赞同 0 条回复
  • sincere 普通 2023年8月14日 下午8:27
    • 思路:第一次遍历统计个数,创建数组,再遍历一次倒插入数组中
    • 复杂度:时间复杂度O(2n),空间复杂度O(n)
    class Solution {
        public int[] reversePrint(ListNode head) {
            if (head == null) {
                return new int[0];
            }
            // 统计链表节点个数
            ListNode tmp = head;
            int count = 0;
            while (tmp != null) {
                count++;
                tmp = tmp.next;
            }
            // 添加元素值
            int[] arrs = new int[count];
            int k = count - 1;
            while (head != null) {
                arrs[k] = head.val;
                k--;
                head = head.next;
            }
            return arrs;
        }
    }
    
    0 赞同 0 条回复
  • . 永久会员 2023年8月14日 下午4:22
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
     //思路就是递归将给的链表从后向前返回,接收到tmp链表中
     //然后new一个数组,遍历tmp链表加入到数组res中就可以
    class Solution {
         ArrayList<Integer> tmp = new ArrayList<Integer>();
        public int[] reversePrint(ListNode head) {
            recur(head);
            //创建一个和tmp链表相同长度的数组
            int[] res = new int[tmp.size()];
            //遍历将tmp链表的节点给加入到数组res中
            for(int i =0;i<res.length;i++){
                 res[i] = tmp.get(i);
            }
            return res;
    
        }
        //递归方法,将链表从后向前加入到另外一个tmp链表中;
      void recur(ListNode head){
          if(head == null) return;
          recur(head.next);
          tmp.add(head.val);
      }
    }
    
    0 赞同 0 条回复
  • 逸兴遄飞 普通 2023年8月14日 下午2:56

    两个方法
    + 方法一:使用递归实现

    class Solution {
        public int[] reversePrint(ListNode head) {
            // 创建缓冲链表
            ListNode lenNode = head;
            int len = 0;
            // 对链表进行遍历,找到链表长度
            while(lenNode != null){
                len++;
                lenNode = lenNode.next;
            }
            // 创建对应长度的数组
            int[] result = new int[len];
    
            // 上面操作后缓冲链表已经被破坏,那么重新初始化
            lenNode = head;
            // 重新遍历链表,并按照倒序将对应元素赋值在数组中
            while(lenNode != null){
                int n = 0;
                n = len - 1;
                result[n] = lenNode.val;
                len--;
                lenNode = lenNode.next;
            }
            return result;
        }
    }
    
    • 方法二:使用栈实现
    // 使用栈实现
    class Solution {
        public int[] reversePrint(ListNode head) {
            // 创建一个栈来从头到尾填入链表的值
            Stack<ListNode> stack = new Stack<ListNode>();
            ListNode temp = head;
            while(temp != null){
                stack.push(temp);
                temp = temp.next;
            }
            // 创建栈对应的长度的数组
            int size = stack.size();
            int[] result = new int[size];
            // 使用pop可以完美实现链表的倒序填入
            for(int i = 0; i < size; i++){
                result[i] = stack.pop().val;
            }
            return result;
        }
    }
    

    时间复杂度O(N),空间复杂度O(1)

    0 赞同 0 条回复
  • 晓宇 普通 2023年8月14日 上午10:45
    class Solution(object):
        def __init__(self):
            self.list = []
    
        def reversePrint(self, head):
            """
            :type head: ListNode
            :rtype: List[int]
            """
            if not head:
                return []
            return self.reversePrint(head.next) + [head.val]
    
    class Solution(object):
        def __init__(self):
            self.list = []
    
        def reversePrint(self, head):
            """
            :type head: ListNode
            :rtype: List[int]
            """
            if not head:
                return []
            self.reversePrint(head.next)
            self.list.append(head.val) 
            return self.list
    

    时间复杂度:O(N),空间复杂度:O(1)
    本题是主要是思考如何使用递归,我第一版本代码思路错了,想着的时候何时append,想着的是尾结点的时候才append第一个,然后根据root.next为空在append,但实际上没必要做任何判断,只需要在后序位置appned即可。

    0 赞同 0 条回复
  • mpweixin用户 普通 2023年8月14日 上午10:10

    时间复杂度:O(N),空间复杂度:O(1)
    先由链表长度确定数组长度,再把数字以相反的排列存放在数组中

    class Solution {
        public int[] reversePrint(ListNode head) {
            int n = 0;
            ListNode pre = head;
    
            while(head!=null){head = head.next;n++;}
            int[] list = new int[n];
            if(pre == null){
                return list;
            }     
    
            for(int i = 0; i
    0 赞同 0 条回复
  • Marc 普通 2023年8月14日 上午1:36
    class Solution:
        def reversePrint(self, head: ListNode) -> List[int]:
            return self.reversePrint(head.next) + [head.val] if head else [] 
    

    时间On 空间On

    0 赞同 0 条回复
  • JustRtn 普通 2023年8月14日 上午12:37

    遍历存储值到vector;
    反转vector;
    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) : val(x), next(NULL) {}
    * };
    */
    class Solution {
    public:
    vector reversePrint(ListNode
    head) {
    vector vec;
    auto *p = head;
    while (p != nullptr) {
    vec.emplace_back(p->val);
    p = p->next;
    }
    reverse(vec.begin(), vec.end());
    return vec;
    }
    };

    0 赞同 0 条回复
  • 别扒拉我 普通 2023年8月13日 下午11:52

    1、迭代遍历

    import java.util.*;
    /**
    *    public class ListNode {
    *        int val;
    *        ListNode next = null;
    *
    *        ListNode(int val) {
    *            this.val = val;
    *        }
    *    }
    *
    */
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
            ArrayList<Integer> res = new ArrayList<>();
            ListNode tmp = listNode;
            while(tmp != null){
                res.add(0, tmp.val);
                tmp = tmp.next;
            }
            return res;
        }
    }
    
    
    1 赞同 0 条回复
  • 天亮说晚安 普通 2023年8月13日 下午10:48

    思路:利用栈存储节点值,出栈到数组返回
    时间复杂度O(n),空间复杂度O(n)

    class Solution {
        public int[] reversePrint(ListNode head) {
            Stack<Integer> stack = new Stack<>();
            ListNode p1 = head;
            while(p1!=null){
                stack.push(p1.val);
                p1 = p1.next;
            }
            int[] res = new int[stack.size()];
            int i=0;
            while(stack.size()>0){
                res[i] = stack.pop();
                i++;
            }
            return res;
        }
    }
    
    1 赞同 0 条回复
  • 木子有点甜🍒 普通 2023年8月13日 下午7:11

    “`python

    Definition for singly-linked list.

    class ListNode:

    def init(self, x):

    self.val = x

    self.next = None

    class Solution:
    def reversePrint(self, head: ListNode) -> List[int]:
    #先用栈写
    #对于每个节点,压入栈(push(node))
    #然后循环出栈,出栈的每个节点存入数组
    # res = []
    # s = []
    # i=0
    # while head:
    # i+=1
    # s.append(head.val)
    # head = head.next

        # while i:
        #     res.append(s.pop())
        #     i-=1
        #这里可以直接通过s[::-1]倒着输出所有元素
    
        # return res
    
        if head==None:
            return []
        else:
            return self.reversePrint(head.next)+[head.val]
    

    “`python

    1 赞同 0 条回复
  • 辰北、 普通 2023年8月13日 下午4:44

    //c 获得链表长度,动态创建数组,赋值数组,反向输出;

    int* reversePrint(struct ListNode* head, int* returnSize){
    struct ListNode* p1=head;
    int i=0;
    while(p1){
    i++;
    p1=p1->next;
    }
    returnSize=i;
    int
    ans=(int)malloc(isizeof(int));
    int n=i-1;
    p1=head;
    while(p1){
    ans[n–]=p1->val;
    // *(ans+i)=p1->val; //倒序将链表元素放入数组
    // i–;
    p1=p1->next;
    }
    free(p1) ;
    return ans;
    }

    1 赞同 0 条回复
  • Jou Siankwa 普通 2023年8月13日 下午4:29
    class Solution {
    
        List<ListNode> list = new ArrayList<>();
        public int[] reversePrint(ListNode head) {
            recur(head);
            int[] res = new int[list.size()];
            for(int i=0;i<list.size();i++){
                res[i] = list.get(i).val;
            }
            return res;
        }
    
        private void recur(ListNode head){
            if(head == null){
                return;
            }
            recur(head.next);
            list.add(head);
        }
    
        public static void main(String[] args) {
            ListNode a1 = new ListNode(1);
            ListNode a2 = new ListNode(3);
            ListNode a3 = new ListNode(2);
    
            a1.next = a2;
            a2.next = a3;
    
            Solution sol = new Solution();
            int[] ints = sol.reversePrint(a1);
    
            for (int anInt : ints) {
                System.out.println(anInt);
            }
    
        }
    }
    

    使用递归,深度遍历

    1 赞同 0 条回复
  • mpweixin用户 普通 2023年8月13日 下午3:48

    時間複雜度 O(n) 空間複雜度 O(n)
    利用遞歸鏈表中的後序遍歷來反向儲存鏈表中的值,

    
    class Solution {
    public:
        vector reversePrint(ListNode* head) {
            traverse(head);
            return res;
        }
    
        int len = 0;  // for initialize len of vector 
    
        vector res;  // store the return value 
     
        int p = 0; // record the index of the current position in vector
    
        void traverse(ListNode* head) {
            if  (head == nullptr) {
                res.resize(len);
                return;
            }
            len++;
            traverse(head->next);
            res[p] = head->val;
            p++;
        }
    };
    
    0 赞同 0 条回复
  • c 普通 2023年8月13日 下午3:24

    时间复杂度O(n),空间复杂度O(n)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] reversePrint(ListNode head) {
            if (head==null){
                return new int[0];
            }
            List<Integer> list = new ArrayList<>();
            process(head,list);
    
            int[] res = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                res[i]=list.get(i);
            }
            return res;
        }
        public static void process(ListNode head,List<Integer> list){
            if (head==null){
                return;
            }
            process(head.next,list);
            list.add(head.val);
        }
    }
    
    0 赞同 0 条回复
  • mpweixin用户 永久会员 2023年8月13日 下午2:20

    时间复杂度O(n),空间复杂度O(n)

    lass Solution {
        public int[] reversePrint(ListNode head) {
            if (head == null) {
                return new int[0];
            }
            return recursive(head, 0);
        }
        public int[] recursive(ListNode node, int len) {
            len++;
            if (node.next == null) {
                int[] ans = new int[len];
                ans[ans.length - len] = node.val;
                return ans;
            }
            int[] ans = recursive(node.next, len);
            ans[ans.length - len] = node.val;
            return ans;
        }
    }
    
    0 赞同 0 条回复
  • 小肸 永久会员 2023年8月13日 下午1:58
    class Solution {
        // public int[] reversePrint(ListNode head) {
        //     ListNode pre = null;
        //     int len = 0;
        //     //反转链表并记录链表长度
        //     while (head != null) {
        //         ListNode nextNode = head.next;
        //         head.next = pre;
        //         pre = head;
        //         head = nextNode;
        //         len ++;
        //     }
        //     int[] res = new int[len];
        //     int index = 0;
        //     while (pre != null && index < len) {
        //         res[index ++] = pre.val;
        //         pre = pre.next;
        //     }
        //     return res;
        // }
        List<Integer> tmp = new LinkedList<>();
        public int[] reversePrint(ListNode head) {
            dfs(head);
            int[] res = new int[tmp.size()];
            int index = 0;
            for (Integer item : tmp) {
                if (index < tmp.size()) {
                    res[index ++] = item;
                }
            }
            return res;
        }
        private void dfs(ListNode head) {
            if (head == null) {
                return;
            }
            dfs(head.next);
            tmp.add(head.val);
        }
    }
    
    0 赞同 0 条回复

# 回答此问题

后才能回答