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

【力扣】206. 反转链表

时间:2021-01-27 14:05:27      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:原来   返回   pre   rev   linked   nod   复杂度   链表   res   

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

public ListNode reverseList(ListNode head) {

        // 时间复杂度 O(n)
        // 空间复杂度 O(1)

        //加入链表为:
            //1 -> 2 -> 3

            //current = 1 result = null

                //进入循环
                //temp = 2 -> 3;
                //current.next = result ;  1 - > null;
                //result = current
        //迭代
        ListNode result = null; //得到结果

        ListNode current = head; //得到当前节点

        while(current != null){

            //暂存当前节点的下一个节点
            ListNode temp = current.next;

            //当前节点的下一个节点设置为result
            current.next = result ;
            result = current;
            //
            current = temp;
        }

        return result;

    }

 

public ListNode reverseList(ListNode head) {

        // 时间复杂度 O(n)
        // 空间复杂度 O(n)  

        //这个太难理解了!!!!!!!!1

        //加入链表为:
            //1 -> 2 -> 3

            // 进入递归
                // head.next = 2 head = 1
                    //在进入递归
                    // head = 2 head.next = 3
                        //再进入递归
                            //直接返回
                        //newHead = 3  
                        // 从原来:2 - > 3 -> null  到现在:2 - > 3(这里就是newHead的指针哇!!!!) -> 2
                        // 2.next = null;
                    //newHead = 3
                    //从原来 1-> 2 -> null 到现在 1-> 2 -> 1
                    //1.next = null;
        //递归
        if(head == null || head.next == null){
            return head;
        }

        //
        ListNode newHead = reverseList(head.next);
        head.next.next =  head;
        head.next = null;

        return newHead;

    }

 

【力扣】206. 反转链表

标签:原来   返回   pre   rev   linked   nod   复杂度   链表   res   

原文地址:https://www.cnblogs.com/fengtingxin/p/14332918.html

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