链表

作者: 九日火 | 来源:发表于2023-07-25 13:57 被阅读0次

    剑指 Offer 06. 从尾到头打印链表

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

    示例 1:
    
    输入:head = [1,3,2]
    输出:[2,3,1]
    
    限制:
    
    0 <= 链表长度 <= 10000
    
    //递归
    func reversePrint(head *ListNode) []int {
        if head == nil {
            return nil
        }
    
        return append(reversePrint(head.Next), head.Val)
    }
    
    //栈
    func reversePrint(head *ListNode) []int {
    
        if head == nil {
            return nil
        }
    
        var pre *ListNode
        for head != nil {
            temp := head.Next
            head.Next = pre
            pre = head
            head = temp
        }
    
        var res []int
        for pre != nil {
            res = append(res, pre.Val)
            pre = pre.Next
        }
        return res
    }
    

    剑指 Offer 24. 反转链表

    定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

    示例:
    
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    
    限制:
    
    0 <= 节点个数 <= 5000
    
    //栈
    func reverseList(head *ListNode) *ListNode {
        if head == nil || head.Next == nil {
            return head
        }
    
        var newhead *ListNode
        for head != nil {
            temp := head.Next
            head.Next = newhead
            newhead = head
            head = temp
        }
    
        return newhead
    }
    
    //递归
    func reverseList(head *ListNode) *ListNode {
        if head == nil || head.Next == nil {
            return head
        }
    
        newHead := reverseList(head.Next)
        head.Next.Next = head
        head.Next = nil
        return newHead
    }
    

    相关文章

      网友评论

          本文标题:链表

          本文链接:https://www.haomeiwen.com/subject/nliqpdtx.html