• 剑指 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("");
    }
    
  • 相关阅读:
    liunx知识点滴积累(1)
    Regsvr32命令的使用
    QTP知识点滴积累
    LoadRunner的Apache的监控
    CMM和过程改进的“妙语” 集锦
    Linux 性能调优的几种方法
    数据库学习笔录(转载)
    Windows性能管理解析
    使用NUnit在.Net编程中进行单元测试
    Google 工程师文化 互助篇
  • 原文地址:https://www.cnblogs.com/fyusac/p/13204886.html
Copyright © 2020-2023  润新知