[Sword offer] 06 Print the linked list from end to beginning

One, the problem

1. Enter the head node of a linked list, and return the value of each node from the end to the beginning (return with an array).

2. Example

Input: head = [1,3,2]

Output: [2,3,1]

3. Restrictions:

0 <= length of linked list <= 10000

Two, the solution

1. Use the characteristics of the stack, last in first out.

2. After putting the data of the linked list into the stack, create an array and assign the data of the battle to the array.

Three, the code

package com.haoxiansheng.demo01.SwordfingerOffer;

import lombok.extern.slf4j.Slf4j;

import java.util.Stack;

/**
 * @author flame
 * @data 2020/10/18
 */
@Slf4j
public class ArrayReverse {
    
    
    public static void main(String[] args) {
    
    
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        log.info("reverseArray=>{}", reverseArray(node1));
    }
    
    // 时间复杂度:O(n)。正向遍历一遍链表,然后从栈弹出全部节点,等于又反向遍历一遍链表。
    //空间复杂度:O(n)。额外使用一个栈存储链表中的每个节点。
    public static int[] reverseArray(Node head) {
    
    
        Stack<Node> stack = new Stack<Node>();
        Node temp = head;
        while (temp != null) {
    
    
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
    
    
            res[i] = stack.pop().value;
        }
        return res;
    }

    static class Node {
    
    
        private int value;
        private Node next;

        public Node(int value) {
    
    
            this.value = value;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_40996741/article/details/109149760