码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 面试题06. 从尾到头打印链表

时间:2020-05-02 20:41:15      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:next   author   官方   solution   gen   时间   date   turn   print   

我的LeetCode:https://leetcode-cn.com/u/ituring/

我的LeetCode刷题源码[GitHub]:https://github.com/izhoujie/Algorithmcii

LeetCode 面试题06. 从尾到头打印链表

题目

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

示例 1:

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

限制:

  • 0 <= 链表长度 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

思路1-两次遍历,一次获得总数建数组,一次存数到数组

算法复杂度:

  • 时间复杂度: $ {\color{Magenta}{\Omicron\left(n\right)}} $
  • 空间复杂度: $ {\color{Magenta}{\Omicron\left(1\right)}} $

思路2-两次遍历,一次用栈存数据建数组,一次保存数到数组

算法复杂度:

  • 时间复杂度: $ {\color{Magenta}{\Omicron\left(n\right)}} $
  • 空间复杂度: $ {\color{Magenta}{\Omicron\left(n\right)}} $

算法源码示例

package leetcode;

import java.util.Stack;

/**
 * @author ZhouJie
 * @date 2020年4月28日 下午6:29:56 
 * @Description: 面试题06. 从尾到头打印链表
 *
 */
public class LeetCode_Offer_06 {

}

//  Definition for singly-linked list.
class ListNode_Offer_06 {
	int val;
	ListNode_Offer_06 next;

	ListNode_Offer_06(int x) {
		val = x;
	}
}

class Solution_Offer_06 {
	/**
	 * @author: ZhouJie
	 * @date: 2020年4月28日 下午6:34:16 
	 * @param: @param head
	 * @param: @return
	 * @return: int[]
	 * @Description: 1-两次遍历,一次统计总数用以建数组,一次用来填数组;
	 *
	 */
	public int[] reversePrint_1(ListNode_Offer_06 head) {
		// 保存头节点
		ListNode_Offer_06 node = head;
		int count = 0;
		// 统计总数
		while (node != null) {
			count++;
			node = node.next;
		}
		int[] rst = new int[count];
		while (head != null) {
			// 倒序放入
			rst[--count] = head.val;
			head = head.next;
		}
		return rst;
	}

	/**
	 * @author: ZhouJie
	 * @date: 2020年4月28日 下午6:35:38 
	 * @param: @param head
	 * @param: @return
	 * @return: int[]
	 * @Description: 2-两次遍历,一次用栈保存,一次从栈放入数组
	 *
	 */
	public int[] reversePrint_2(ListNode_Offer_06 head) {
		int count = 0;
		Stack<Integer> stack = new Stack<Integer>();
		while (head != null) {
			stack.push(head.val);
			head = head.next;
			count++;
		}
		int[] rst = new int[count];
		int i = 0;
		while (!stack.isEmpty()) {
			rst[i++] = stack.pop();
		}
		return rst;
	}
}

LeetCode 面试题06. 从尾到头打印链表

标签:next   author   官方   solution   gen   时间   date   turn   print   

原文地址:https://www.cnblogs.com/izhoujie/p/12819301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!