LeetCode 第25题 k个一组翻转链表

LeetCode 第25题
有些题代码写的还是挺优美的。哈哈
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(null == head || k == 1) {
            return head;
        }
        ListNode res = fun(head, k, head);
        return res;
    }
	public boolean checkNodeEnough(ListNode head, int k) {
        int count = 0;
        ListNode temp = head;
        while(temp != null && count < k) {
            count++;
            temp = temp.next;
        }
        return count < k ? false : true;
    }
	public ListNode fun(ListNode head, int k, ListNode tail) {
        ListNode temp = head;
        int count = 1;
        while(count < k) {
            count++;
            head = tail.next;
            tail.next = head.next;
            head.next = temp;
            temp = head;
        }
        
        if(checkNodeEnough(tail.next, k)) {
            tail.next = fun(tail.next, k, tail.next);
        }
        return temp;
    }
}

最近LeetCode的内存消耗有点不准确,总是显示击败5%左右的用户,我的写法里,这道题的空间复杂度应该是O(1)
时间复杂度应该是O(n),只是遍历了两次链表
在这里插入图片描述

补一个遇到的面试题,k个一组翻转的简化版
在这里插入图片描述

class Solution {
    public ListNode reverseBetween (ListNode head, int m, int n) {
        if(m == n){
            return head;
        }
        ListNode res = head;
        int count = 1;
        ListNode before = head;
        while(count < m){
            before = head;
            head = head.next;
            count++;
        }
        int changeCount = 0;
        ListNode tempHead = head;
        while(changeCount < n-m){
            ListNode temp = head.next;
            head.next = temp.next;
            temp.next = tempHead;
            tempHead = temp;
            changeCount++;
        }
        if(before != head){
            before.next = tempHead;
        }
        if(res == head){
            return tempHead;
        }
        return res;
    }
}

面试的时候不能debug,有点小细节还是蛮难想的,不debug还真不好完全解出来
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值