• 剑指 Offer 06. 从尾到头打印链表


    import java.util.Deque;
    import java.util.LinkedList;
    import java.util.Stack;
    
    /**
     * @Class ReversePrint
     * @Description 剑指 Offer 06. 从尾到头打印链表
     * 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
     *
     * 示例 1:
     * 输入:head = [1,3,2]
     * 输出:[2,3,1]
     *
     * 限制:
     * 0 <= 链表长度 <= 10000
     * @Author
     * @Date 2020/6/28
     **/
    public class ReversePrint {
        static class ListNode {
            int val;
            ListNode next;
            ListNode(int x) {
                val = x;
            }
        }
    }
    
    /**
     * 解法1:利用栈
     */
    public static int[] reversePrint(ListNode head) {
    	ListNode listNode = head;
    	Stack<Integer> integerDeque =new Stack<>();
    	int count =0;
    	while (listNode!= null){
    		integerDeque.push(listNode.val);
    		listNode = listNode.next;
    		count++;
    	}
    	int[] ans = new int[count];
    	for (int i = 0; i <count ; i++) {
    		ans[i] = integerDeque.pop();
    	}
    	return ans;
    }
    
    /**
     * 解法2:利用递归
     */
    public static int[] reversePrint(ListNode head) {
    	LinkedList<Integer> linkedList = new LinkedList<>();
    	reversePrint(head,linkedList);
    	int size = linkedList.size();
    	int[] ans = new int[size];
    	for (int i = 0; i < size; i++) {
    		ans[i]= linkedList.pop();
    	}
    	return ans;
    }
    
    private static LinkedList<Integer> reversePrint(ListNode listNode, LinkedList linkedList){
    	if(listNode==null) return null;
    	linkedList.add(listNode.val);
    	return reversePrint(listNode.next,linkedList);
    }
    
    // 测试用例
    public static void main(String[] args) {
    	ListNode listNode11 = new ListNode(1);
    	ListNode listNode12 = new ListNode(3);
    	listNode11.next = listNode12;
    	ListNode listNode13 = new ListNode(2);
    	listNode12.next = listNode13;
    	listNode13.next = null;
    
    	int[] ans = reversePrint(listNode11);
    	System.out.println("demo01 result:");
    	for (int val : ans){
    		System.out.print(" "+val);
    	}
    	System.out.println("");
    }
    
  • 相关阅读:
    CodeForces 670E Correct Bracket Sequence Editor
    CodeForces 670F Restore a Number
    HDU 5895 Mathematician QSC
    HDU 5880 Family View
    HDU 5886 Tower Defence
    CSS3.16
    CSS页面定制代码+动漫人物设计
    TSP变形(三进制状压)
    三进制状压(涂抹果酱)
    最小点覆盖(König定理)
  • 原文地址:https://www.cnblogs.com/fyusac/p/13204886.html
Copyright © 2020-2023  润新知