206. Reverse Linked List

一、题目

  1、审题

  

  2、分析

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

 

二、解答

  1、思路:

    方法一、

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

    // iteratively
    public ListNode reverseList(ListNode head) {
        
        if(head == null)
            return null;
        
        ListNode pre = null;
    ListNode cur = head; ListNode next = null; while(cur != null) { 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);
    }

 

posted @ 2018-10-20 17:49  skillking2  阅读(93)  评论(0编辑  收藏  举报