从尾到头打印链表

此博客链接:https://www.cnblogs.com/ping2yingshi/p/13362249.html

题目链表:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

 

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]
题解:
思路:
1.先把链表反转。
2.定义一个数组,把反转后的链表中的数据域赋值给数组。
3.返回数组。
注意:当提交时,会出现链表为空的情况,但是链表为空时,需要返回的时[]而不是null.此师返回空数组,需要定义一个空数组。使用如下形式
if(head==null)
        return new int[]{};
代码如下:
class Solution {
    public int[] reversePrint(ListNode head) {
       if(head==null)
        return new int[]{};
        ListNode newnode=new ListNode(0);
        ListNode newtemp=new ListNode(head.val);
        newnode.next=newtemp;
        newtemp.next=null;
        head=head.next;
        int count=0;
        while(head!=null)
        {
            ListNode temp=head;
            head=head.next;
            temp.next=newtemp;
            newtemp=temp;
            newnode.next=temp;
            count++;
        }
        newnode=newnode.next;
        int ans[]=new int[count+1];
        for(int i=0;i<=count;i++)
        {
           ans[i]=newnode.val;
           newnode=newnode.next;
        }
       return ans;

 

posted @ 2020-07-22 17:49  萍2樱释  阅读(151)  评论(0编辑  收藏  举报