继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【LEETCODE】模拟面试-206. Reverse Linked List

Alice嘟嘟
关注TA
已关注
手记 209
粉丝 75
获赞 279

图:新生大学

https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

**input: **a single linked list
output: a list node head of the reverse list of given input
**corner: **when the list is null, or only contains one head

What we want to do is to reverse the list.
So we scan from head to tail.
For every two nodes cur and cur.next, we will make cur point to its forward node.

So at each step, we need a node pre to keep connection with current scanner, so that cur.next = pre.
And we also need a node nextOne to memorize cur.next, since it will be changed during the scanner, if without track, cur will lose its way to next scanner.

In order to move to next scanner, pre will move to cur, and cur will move to nextOne.

Until cur moves to tail null, pre is currently the new head of the reversed list, so just return it.

The idea of Recursion is similar with Iteration, what to do in current scanner is to keep track of nextOne and point to pre, and what to prepare for next step is to pass nextOne and cur as the new 'cur' and 'pre'.

//iterationpublic class Solution{    public ListNode reverseList(ListNode head){        //corner
        if ( head == null || head.next == null ){            return head;
        }
        
        ListNode pre = null;
        ListNode cur = head;        while ( cur != null ){            //reverse
            ListNode nextOne = cur.next;
            cur.next = pre;            //prepare
            pre = cur;
            cur = nextOne;
        }        
        return pre;
    }
}//recursionpublic class Solution{    public ListNode reverseList(ListNode head){        //corner
        if ( head == null || head.next == null ){            return head;
        }
        
        ListNode pre = null;        
        return helper(head, pre);
    }    
    public ListNode helper(ListNode cur, ListNode pre){        //base
        if ( cur == null ){            return pre;
        }        
        //current
        ListNode nextOne = cur.next;
        cur.next = pre;        
        //next
        return helper(nextOne, cur);
    }
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP