从头到尾打印链表

一.目标:输入一个链表,从尾到头打印链表每个节点的值。
二.思路:链表应该只是遍历一遍,因为从尾到头翻转太麻烦,可以用一个ArrayList记录值,然后翻转ArrayList。
三.易错点:
1.获取ArrayList长度用 .size(),string用 .length(),[] 用.length。
2.取值方法为 get 和 set 。
3.应该for到长度的一半,如果for全部的话就是又翻了回来。
四.代码

package offer;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class printListFromTailToHeadTest {

    public static void main(String[] args) {
        printListFromTailToHeadTest t1 = new printListFromTailToHeadTest();
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode three = new ListNode(3);
        ListNode four = new ListNode(4);
        ListNode five = new ListNode(5);

        one.next = two;
        two.next = three;
        three.next = four;
        four.next = five;
        ArrayList<Integer> result = t1.printListFromTailToHead(one);

        System.out.println(result);

    }

    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        //get the val;
        ArrayList<Integer> re = new ArrayList<Integer>();
        if(listNode == null){
            return re;
        }
        //ArrayList<Integer> re = new ArrayList<Integer>();
        ListNode dummy = new ListNode(0);
        dummy.next = listNode;
        while(dummy.next != null){
            re.add(dummy.next .val);
            dummy.next = dummy.next .next ;
        }
        //reverse the val;
        int length = re.size();
        //System.out.println(length);
        for(int i = 0; i < length / 2 ; i++){
            int temp = re.get(i);
            re.set(i, re.get(re.size() - 1 -i));
            re.set(re.size() - 1 -i, temp);
        }
        return re;
}

}
class ListNode {
        int val;
        ListNode next = null;
        ListNode(int val) {
            this.val = val;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值