zoukankan      html  css  js  c++  java
  • 剑指Offer06.从尾到头打印链表

    题目

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

    示例 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
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题方法

    迭代

    递归

    反转链表

    反转数组

    代码

    // 栈  时间复杂度O(n) 空间复杂度O(n)
    func reversePrint(head *ListNode) (res []int) {
    	var stack []*ListNode
    	// 压入栈
    	for head != nil {
    		stack = append(stack, head)
    		head = head.Next
    	}
    	// 弹出栈
    	for len(stack) != 0 {
    		res = append(res, stack[len(stack)-1].Val)
    		stack = stack[:len(stack)-1]
    	}
    	return res
    }
    
    // 遍历 时间复杂度O(N) 空间复杂度O(1)
    func reversePrint2(head *ListNode) []int {
    	var ans []int
    	for head != nil {
    		ans = append([]int{head.Val}, ans...)
    		head = head.Next
    	}
    	return ans
    }
    
    // 递归
    func reversePrint3(head *ListNode) []int {
    	if head == nil{
    		return nil
    	}
    	return append(reversePrint3(head.Next),head.Val)
    }
    
    // 反转链表
    func reversePrint4(head *ListNode) (res []int) {
    	if head == nil{
    		return nil
    	}
    	// 反转链表
    	var pre *ListNode
    	for head != nil{
    		next := head.Next
    		head.Next = pre
    		pre = head
    		head = next
    	}
    	for pre != nil{
    		res = append(res,pre.Val)
    		pre = pre.Next
    	}
    	return res
    }
    
    // 反转数组
    func reversePrint5(head *ListNode) (res []int) {
    	if head == nil{
    		return nil
    	}
    	// 顺序存储结果
    	for head != nil{
    		res = append(res,head.Val)
    		head = head.Next
    	}
    	// 将结果倒序
    	for i,j := 0,len(res)-1;i < j;{
    		res[i],res[j] = res[j],res[i]
    		i++
    		j--
    	}
    	return res
    }
  • 相关阅读:
    第二类斯特林数学习笔记
    [ZJOI2017]树状数组
    「LibreOJ Round #6」花火
    [Ynoi2016]这是我自己的发明 莫队
    codeforces706E
    扩展CRT
    PKUSC2018游记
    「PKUWC 2018」Minimax
    「SHOI2015」(LOJ2038)超能粒子炮・改
    Codeforces712E
  • 原文地址:https://www.cnblogs.com/hzpeng/p/15099358.html
Copyright © 2011-2022 走看看