首页 > 其他 > 详细

剑指Offer_编程题-003 - 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList

时间:2019-07-10 19:27:32      阅读:120      评论:0      收藏:0      [点我收藏+]

如题 (总结)

借鉴学习文章列表

  • 链接1:
  • 链接2:
  • ALiBaBaJavaCodingGuideLines

1.ListNode


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

    public ListNode() {
    }

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

    public ListNode getNext() {
        return next;
    }

    public void setNext(ListNode next) {
        this.next = next;
    }



    public void setVal(int val) {
        this.val = val;
    }
}

2. Solution代码

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

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {

        if(listNode==null){
            return  new ArrayList<>();
        }
        Stack<Integer> stack = new Stack<>();

        ListNode t = listNode;
        while (t!=null){
          stack.push(t.val);
          t = t.next;
        }
        ArrayList<Integer> arrayList = new ArrayList<>(stack.size());

        while(!stack.empty()){
            arrayList.add(stack.pop());
        }
        return arrayList;

    }
}

3.Test测试


public class Test {
    public static void main(String[] args) {

        ListNode listNode = new ListNode();

        int arr[] = {67,0,24,58};
        ListNode next =listNode;
        for(int i : arr){
            next.setVal(i);
            //注意, 面向题解答案编程后发现, 最后的链表末尾是不设置结点的!坑!
            if(i!=58){
                next.setNext(new ListNode());
                next = next.getNext();
            }

        }
        Solution solution = new Solution();
        ArrayList<Integer> arrayList = solution.printListFromTailToHead(listNode);
        for(Integer i: arrayList){
            System.out.println(i+"\t");
        }
    }
}

测试结果

58  
24  
0   
67  

剑指Offer_编程题-003 - 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList

原文:https://www.cnblogs.com/zhazhaacmer/p/11165784.html

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