Leetcode 经典题目反转链表三部曲

1.直接反转一个链表

这个题目在面试中是会考察的,因为代码量很少,要掌握

class Solution{
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, pre = null;
        while(cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

这个是要直接写出来的,包括手写

 

2.反转一段链表的第n个节点到第m个节点

这个有种种边界条件要考虑,是不容易一次性就正确的写出来的。

优雅的代码是封装一个函数,反转从begin节点到end节点之间的节点。

这里要注意,反转的链表是不包括begin和end,原因是反转中间链表会影响到两边,为了代码的高内聚,低耦合,应该把两边的begin和end也加上

public ListNode reverse(ListNode begin, ListNode end)

 这里的反转逻辑如下

    /* 1->2->3->4->5
       1<-     2<-    3   <-     4     ->5
       |       |                 |      |
       begin   first             pre    cur

       1->4->3->2->5
    */

除了中间反转逻辑,还有前后的处理,为了检验这段代码的鲁棒性,可以传入dummy和null来验制反转整个链表

    public ListNode reverse(ListNode begin, ListNode end){
        ListNode cur = begin.next, pre = begin, first = cur;    // first 作为尾节点返回
        while(cur!=end) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        begin.next = pre;
        first.next = cur;
        return first;
    }

3. K个链表反转一次

这个是最难的题目,首先要实现上面的函数,同时还要有遍历逻辑,要边画图边思考,面试中做出来还是不容易。

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int count = 0;
        ListNode cur = dummy.next, begin = dummy, end = null;
        while(cur!=null){
            count++;
            if(count%k==0){
                begin = reverse(begin, cur.next);
                cur = begin.next;
            }
            else{
                cur = cur.next;
            }
        }
        return dummy.next;
    }
    /*
    翻转begin到end之间的链表(不包括begin和end, 并返回最后一个节点)
    输入: 1->2->3->4->5->NULL, m = 2, n = 4
    输出: 1->4->3->2->5->NULL
    1     1<-2<-3<-4->5
     */
    public ListNode reverse(ListNode begin, ListNode end){
        ListNode cur = begin.next, pre = begin, first = cur;    // first 作为尾节点返回
        while(cur!=end) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        begin.next = pre;
        first.next = cur;
        return first;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值