前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[面试题06]从未到头打印链表(LeetCode-剑指Offer)

[面试题06]从未到头打印链表(LeetCode-剑指Offer)

作者头像
手撕代码八百里
发布2020-07-28 09:24:06
2700
发布2020-07-28 09:24:06
举报
文章被收录于专栏:猿计划
代码语言:javascript
复制
//输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 
//
// 
//
// 示例 1: 
//
// 输入:head = [1,3,2]
//输出:[2,3,1] 
//
// 
//
// 限制: 
//
// 0 <= 链表长度 <= 10000 
//


//leetcode submit region begin(Prohibit modification and deletion)

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head!=null){
            list.add(head.val);
            head = head.next;
        }

        int [] in = new int[list.size()];

        for (int i = list.size()-1; i >= 0 ; i--) {
            in[(list.size()-i-1)] = list.get(i);
        }

        return in;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

用了三种办法来做了,其他两种都不太理想:

第二种

代码语言:javascript
复制
 static  public int[] reversePrint(ListNode head) {
        StringBuffer sb = new StringBuffer();

        while (head!=null){
            sb.append(head.val);
            head = head.next;
        }


        int [] in = new int[sb.length()];

//        for (int i =   sb.length()-1; i >= 0; i--) {
//            System.out.println("a="+sb.charAt(i)+"---->"+(sb.length()-i-1));
//        }

        for (int i = sb.length()-1; i >= 0 ; i--) {
            in[(sb.length()-i-1)] = Integer.valueOf(String.valueOf(sb.charAt(i)));
        }

        return in;
    }

第三种

代码语言:javascript
复制
public int[] reversePrint1(ListNode head) {
        String s = "";
        while (head!=null){

            s = s +head.val + ",";
            head = head.next;
        }

        s = s.substring(0,s.length()-1); //去掉最后一个空格。

        String[] split = s.split(",");
        for (int i = 0; i < split.length; i++) {

        }

        int [] in = new int[split.length];

        int j = 0;
        for (int i = split.length-1; i >= 0 ; i--) {
            in[j] = Integer.valueOf(split[i]);
            j++;
        }
        return in;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/03/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 用了三种办法来做了,其他两种都不太理想:
  • 第二种
  • 第三种
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档