2020-04-07(206. 反转链表*)

难度 简单
迭代的方法比较多。
方法一:低效率迭代法。这是第一遍完成的,对于1->2->3->4->5->null,设置一个指针在头部,一个指针在尾部,然后不断把头部的元素移动到尾部。执行出来时间不理想。
执行用时 :1 ms, 在所有 Java 提交中击败了7.03%的用户
内存消耗 :39 MB, 在所有 Java 提交中击败了5.46%的用户

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode cur = head.next;
        int n = 1;
        while(cur.next != null){
            cur = cur.next;
            n++;
        }
        while(head != cur){
            ListNode temp = new ListNode(head.val);
            temp.next = cur.next;
            cur.next = temp;
            head = head.next;
        }
        return head;
    }

方法二:高效迭代法。从第一个元素还是构建一个新的队列。
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :39.1 MB, 在所有 Java 提交中击败了5.46%的用户

public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode nHead = new ListNode(head.val);
        nHead.next = null;
        head = head.next;
        while(head != null){
            ListNode cur = new ListNode(head.val);
            cur.next = nHead;
            nHead = cur;
            head = head.next;
        }
        return nHead;
    }

方法三:迭代法 c
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :40.2 MB, 在所有 Java 提交中击败了5.46%的用户

    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode nHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return nHead;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容