首页 > 其他 > 详细

206. Reverse Linked List

时间:2018-10-20 19:20:05      阅读:177      评论:0      收藏:0      [点我收藏+]

一、题目

  1、审题

  技术分享图片

  2、分析

    分别采用递归、迭代的方式将链表进行翻转。

 

二、解答

  1、思路:

    方法一、

      迭代: 采用两个指针 pre、cur

    // iteratively
    public ListNode reverseList(ListNode head) {
        
        if(head == null)
            return null;
        
        ListNode pre = head, cur = head.next;
        pre.next = null;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        
        return pre;
    }

 

  方法二、

  递归:

    public ListNode reverseList3(ListNode head) {
        return reverseListHelper(head, null);
    }
    private ListNode reverseListHelper(ListNode head, ListNode newHead) {
            
        if(head == null)
            return newHead;
        ListNode next = head.next;
        head.next = newHead;
        return reverseListHelper(next, head);
    }

 

206. Reverse Linked List

原文:https://www.cnblogs.com/skillking/p/9822443.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!