首页 > 其他 > 详细

从尾到头打印链表

时间:2020-07-22 18:56:37      阅读:55      评论:0      收藏:0      [点我收藏+]

此博客链接: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;

 

从尾到头打印链表

原文:https://www.cnblogs.com/ping2yingshi/p/13362249.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!