zoukankan      html  css  js  c++  java
  • 剑指 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("");
    }
    
  • 相关阅读:
    Node.js
    EFCore-Migrations
    C#核心语法
    C#编程总结--总目录
    PHP ServerPush
    汉字转拼音
    用五分钟重温委托,匿名方法,Lambda,泛型委托,表达式树
    Sublime Text 3 绝对神器
    多线程学习总结
    分享: 利用Readability解决网页正文提取问题
  • 原文地址:https://www.cnblogs.com/fyusac/p/13204886.html
Copyright © 2011-2022 走看看