《剑指offer》面试题的Java实现-从尾到头打印链表

发布时间 2023-10-10 21:11:53作者: 深海、
输⼊⼀个链表的头节点,按链表从尾到头的顺序返回每个节点的值(⽤数组返回)。⽐如下⾯的链表:

 

public static class LinkNode{

    int value;
LinkNode next;
LinkNode(int value){
this.value = value;
}
}
//思路:将链表进行遍历,在遍历的过程中记录元素的个数,
//然后new一个新的int类型的数组,数组大小就是遍历到的元素个数,
//之后通过从后往前插入元素的方法将链表中的元素插入到数组中
public static int[] solution4_1(LinkNode head){
if(head == null)
return new int[0];
//记录链表中元素的个数
int count = 0;
LinkNode temp = head;
while(temp!=null){
count ++;
temp = temp.next;
}

int []res = new int[count];
int k = count - 1;
while(head!=null){
res[k--] = head.value;
head = head.next;
}
return res;
}