首页 > 其他 > 详细

[剑指offer]从尾到头打印链表

时间:2019-08-26 19:04:36      阅读:94      评论:0      收藏:0      [点我收藏+]

 

题目描述

 

 

package com.sunshine.OFFER66_SECOND;

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

 

 

package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Stack;

public class A3_printListFromTailToHead {


    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        node1.next=node2;
        node2.next=node3;
        ArrayList<Integer> arrayList = printListFromTailToHead(node1);
        arrayList.forEach(a->System.out.println(a));
        ArrayList<Integer> arrayList2 = printListFromTailToHead2(node1);
        arrayList2.forEach(a->System.out.println(a));
    }

    //
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> answer = new ArrayList<>();
        Stack<Integer> stack=new Stack<>();
        while(null !=listNode){
            stack.push(listNode.val);
            listNode=listNode.next;
        }
        while(!stack.empty()){
            answer.add(stack.pop());
        }
        return answer;
    }
    //集合库
    public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        ArrayList<Integer> answer = new ArrayList<>();
        while(null !=listNode){
            answer.add(listNode.val);
            listNode=listNode.next;
        }
        Collections.reverse(answer);
        return answer;
    }
    //其他还有递归等
}

 

[剑指offer]从尾到头打印链表

原文:https://www.cnblogs.com/MoonBeautiful/p/11413935.html

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