美文网首页
【剑指24】单链表反转

【剑指24】单链表反转

作者: 浅浅星空 | 来源:发表于2019-07-10 23:45 被阅读0次

    题目描述

    输入一个链表,反转链表后,输出新链表的表头。

    代码

        //1.递归
        public ListNode ReverseList(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode pre = head;
            ListNode next = head.next;
            pre.next = null;
            ListNode retrunNode = ReverseList(next);
            next.next = pre;
            return retrunNode;
        }
    
        //2.迭代
        public ListNode ReverseList2(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode pre = head;
            ListNode next = head.next;
            while (next != null) {
                ListNode temp = next.next;
                next.next = pre;
                pre = next;
                next = temp;
            }
            head.next = null;
            return pre;
        }
    

    相关文章

      网友评论

          本文标题:【剑指24】单链表反转

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