为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
机器学习

图:新生大学

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);
    }
}


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消