Prove safety offer three: list print head from the tail

 Title Description

Enter a list, the value returned by a ArrayList list sequentially from the tail to the head.

package com.jianzhioffer;

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

public class ReverseList {
	public static void main(String[] args){
		ListNode l1 = new ListNode(1);
		ListNode l2 = new ListNode(2);
		ListNode l3 = new ListNode(3);
		ListNode l4 = new ListNode(4);
		ListNode l5 = new ListNode(5);
		
		l1.next = l2;
		l2.next = l3;
		l3.next = l4;
		l4.next = l5;

		ArrayList<Integer> list = printListFromTailToHead(l1);
		for(Integer i : list){
			System.out.println(i);
		}
		list = printListFromTailToHeadByStack(l1);
		for(Integer i : list){
			System.out.println(i);
		}
	}
	
	// 利用ArrayList的add方法
	public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
		
		ArrayList<Integer> list = new ArrayList<Integer>();
		if(null == listNode)
			return list;
		
		ListNode temp = listNode;
		while(temp != null){
			list.add(0, temp.val);
			temp = temp.next;
		}
		
		return list;
	}
	
	// 利用Stack
	public static ArrayList<Integer> printListFromTailToHeadByStack(ListNode listNode) {
		
		ArrayList<Integer> list = new ArrayList<Integer>();
		if(null == listNode)
			return list;
		
		Stack<Integer> stack = new Stack<Integer>(); 
		ListNode temp = listNode;
		while(temp != null){
			stack.push(temp.val);
			temp = temp.next;
		}
		while(!stack.isEmpty()){
			list.add(stack.pop());
			
		}
		return list;
	}
}


class ListNode {
    int val;
    ListNode next = null;

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

 

 

 Summary: This question is relatively simple, there are many solutions, a method of: using ArrayList add method, the circular linked list, each linked list is added to the value of a first position of ArrayList, thus achieving added to the list from the tail to the head to the ArrayList.

   Method 2: Using the Stack class, a circular linked list, each node in the linked list pressed into the stack, and the stack, the stack value will be added to the ArrayList. This can also be achieved from the tail added to the ArrayList head.

  Method three: The reverse list, then the list of reverse circulation can.

Guess you like

Origin blog.csdn.net/m0_37564426/article/details/91794158