剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思路1:翻转链表
翻转链表,然后从头打印
翻转链表使用递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//边界条件
if(head == null) return new int[]{};
if(head.next == null) return new int[]{head.val};
//求出链表长度
ListNode currentNode = head;
int count = 0;
while(currentNode != null){
count++;
currentNode = currentNode.next;
}
//又链表长度,建立数组
int[] resultArray = new int[count];
//翻转链表
ListNode newHead = reverseList(head);
//将翻转后的链表值,存储在数组里面
for(int i = 0; i < count; i++){
resultArray[i] = newHead.val;
newHead = newHead.next;
}
return resultArray;
}
public ListNode reverseList(ListNode head){
if(head == null) return null;
if(head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
时间复杂度:O(3*n) = O(n)
空间复杂度:
链表翻转使用非递归:
public ListNode reverseList(ListNode head){
if(head == null) return null;
if(head.next == null) return head;
ListNode newHead = new ListNode();
while(head != null){
ListNode tempNode = head.next;
head.next = newHead.next;
newHead.next = head;
head = tempNode;
}
return newHead.next;
}
时间复杂度:O(3*n) = O(n)
空间复杂度:O(n)
思路2:
求出链表长度,建立数组,将第一个节点值,存储在数组最后一个元素里面,依次类推
class Solution {
public int[] reversePrint(ListNode head) {
//边界条件
if(head == null) return new int[]{};
if(head.next == null) return new int[]{head.val};
//求出链表长度
ListNode currentNode = head;
int count = 0;
while(currentNode != null){
count++;
currentNode = currentNode.next;
}
//根据链表长度,建立数组
int[] resultArray = new int[count];
//将链表值,存储在数组里面
for(int i = 0; i < count; i++){
resultArray[count - i - 1] = head.val;
head = head.next;
}
return resultArray;
}
}
时间复杂度:O(2*n) = O(n)
空间复杂度:O(n)
本文介绍了一种算法,该算法接收一个链表头节点,并从尾到头返回链表每个节点的值。通过两种方法实现:一是翻转链表再打印;二是直接按逆序填充数组。提供了详细的代码实现及时间、空间复杂度分析。
787

被折叠的 条评论
为什么被折叠?



