美文网首页
链表的反转

链表的反转

作者: Peter杰 | 来源:发表于2019-08-26 19:12 被阅读0次
    //递归
            public ListNode reverseList(ListNode head) {
                if (head == null) {
                    return null;
                }
                if (head.next==null) {
                    return head;
                }
                ListNode newHead = reverseList(head.next);
                head.next.next = head;
                head.next = null;
                return newHead;
            }
            //非递归
            public ListNode reverseList2(ListNode head) {
                if (head == null) {
                    return null;
                }
                if (head.next==null) {
                    return head;
                }
                ListNode newHead = null;
                while (head != null) {
                    ListNode tmp = head.next;
                    head.next = newHead;
                    newHead = head;
                    head = tmp;
                }
                return newHead;
            }
    

    相关文章

      网友评论

          本文标题:链表的反转

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