前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LEETCODE】模拟面试-206. Reverse Linked List

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

作者头像
杨熹
发布2018-04-03 15:03:59
6990
发布2018-04-03 15:03:59
举报
文章被收录于专栏:杨熹的专栏

图:新生大学

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'.

代码语言:javascript
复制
//iteration
public 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;
    }
}

//recursion
public 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);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.01.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档