当前位置:网站首页>Sword finger offer 06 Print linked list from beginning to end

Sword finger offer 06 Print linked list from beginning to end

2022-07-05 05:28:00 ThE wAlkIng D

Title Description

 Insert picture description here

Problem analysis

1. Because the input and output are arrays , So create a new array , It is used to store the array after inversion, that is, the array from tail to head
2. Next, take out the length of the array and assign it to the new array
3. The value of the header node is assigned to the new array , Then go back ,

Code instance

/** * 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 node = head;
       int len = 0;
       while(node != null){
    
       		len++;
       		node = node.next;// Fetch the original length of the array 
       }
       int[] nums = new int[len];
       while(head != null){
    
       		nums[--len] = head.val;// The array stores the values of each node from beginning to end 
       		head = head.next;
       }
       return nums;
    }
}


/** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead(); */
    }
}
原网站

版权声明
本文为[ThE wAlkIng D]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050525449678.html