剑指offer06:从尾到头打印链表
1、题目
剑指offer06:从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例1:
输入:head = [1,3,2]
输出:[2,3,1]
2、代码
2.1、方案1:递归法
先走至链表尾端,回溯时依次将节点值加入列表,然后将列表转为数组即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> tmp = new ArrayList<>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i=0;i<res.length;i++){
res[i] = tmp.get(i);
}
return res;
}
//递归
public void recur(ListNode head){
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
}
2.2、方案2:辅助栈法
利用栈后进先出的特性。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head != null) {
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i = 0; i < res.length; i++)
res[i] = stack.pop();
return res;
}
}
3、随笔
3.1、定义单链表
public class ListNode {
int val;//元素值
ListNode next;//下一个节点
ListNode(int x) { val = x; }//构造方法,元素值的初始化
}
示例:
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode firstNode = new ListNode(3);
ListNode secondNode = new ListNode(2);
head.next = firstNode;
firstNode.next = secondNode;
int[] res = reversePrint(head);
System.out.print("[" );
for(int i=0;i<res.length;i++){
if(i==res.length-1) {
System.out.print(res[i]);
}else {
System.out.print(res[i]+",");
}
}
System.out.print("]" );
}
3.2、递归
传递+回归
3.3、列表
1、列表的定义
ArrayList<Integer> tmp = new ArrayList<>();
2、列表常见的方法
(1)size()
列表的长度。
示例:
tmp.size();
(2)get()
根据索引获取列表中的元素值。
示例:
tmp.get(i);
结语
如果你喜欢我写的文章,欢迎来踩我个人搭建的博客~
ChengNing’s Blog