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

    科技2022-07-13  141

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

    示例 1:

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

    限制:

    0 <= 链表长度 <= 10000

     方法一:

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int[] reversePrint(ListNode head) { ListNode temp = head; int length = 0; while(temp != null){ length++; temp = temp.next; } int[] ls = new int[length]; for(int i=ls.length-1;i>=0;i--){ ls[i] = head.val; head = head.next; if(head == null){ break; } } return ls; } }

     

      方法二:使用栈:

       

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ import java.util.*; class Solution { public int[] reversePrint(ListNode head) { Stack<ListNode> stack = new Stack<>(); while(head!=null){ stack.add(head); head = head.next; } int[] ls = new int[stack.size()]; for(int i=0;i<ls.length;i++){ ls[i] = stack.pop().val; } return ls; } }

     

    Processed: 0.010, SQL: 8