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


    输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

    示例 1:

    输入:head = [1,3,2]
    输出:[2,3,1]

    限制:

    0 <= 链表长度 <= 10000

    题解:

    使用栈,后进先出的特点。

    从链表头开始,依次将节点入栈,然后依次弹出栈内元素并存储到数组中

    • 创建一个栈,用于存储链表的节点
    • 创建一个指针,初始时指向链表的头节点
    • 当指针指向的元素非空时,重复下列操作:
      • 将指针指向的节点压入栈内    
      • 将指针移到当前节点的下一个节点
    public class offer06 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ListNode head = new ListNode(1);
            head.next = new ListNode(3);
            head.next.next = new ListNode(2);
            
            int[] arr = reversePrint(head);
            for(int i:arr){
                System.out.print(i+" ");
            }
        }
    
        public static int[] reversePrint(ListNode head) {
            Stack<ListNode> stack = new Stack();//创建栈
            ListNode temp = head;//创建指向head的指针
            while(temp!=null){
                stack.push(temp);
                temp = temp.next;
            }
            
            int size = stack.size();
            int[] arr = new int[size];
            
            for(int i=0;i<size;i++){
                arr[i] = stack.pop().val;
            }
            return arr;
        }
    }
    
    /**
     * 单链表列表
     * @author Administrator
     *
     */
    class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }
  • 相关阅读:
    Pythonbreak
    Python水仙花数
    Pythoncontinue
    Python二重循环中的break与continue
    Python列表元素的添加操作
    OpenAPI中规范的数据类型
    NSSM创建服务
    事件模式为什么要求sender的参数时Object类型
    Jenkins踩坑
    C# InfluxDB批量插入
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/14928919.html
Copyright © 2020-2023  润新知