Offer_ prove safety program title -003-- input a list, the value returned from the sequence list by the end head of an ArrayList

If that (summary)

Learn from the article list

  • Link 1:
  • Link 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 Code

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 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");
        }
    }
}

Test Results

58  
24  
0   
67  

Guess you like

Origin www.cnblogs.com/zhazhaacmer/p/11165784.html