[LeetCode] Reverse Nodes in k-Group

在上一个题的基础上改动了一下,因为内存受限,所以每次都从头寻找指定的节点,并单独实现了一个函数。

可读性比较差,估计过几天就看不懂自己写的了。不知道别人有什么更好的办法。等有空的时候好好研究一下链表的操作。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode resultHead = new ListNode(0);
        resultHead.next = head;

        ListNode tempHead = new ListNode(-1);
        tempHead.next = resultHead;

        ListNode tempEnd = new ListNode(-1);

        ListNode lastNode = getNextNode(tempHead, k + 1);
        if (lastNode == null) {
            return resultHead.next;
        }

        while (lastNode != null) {
            ListNode theNextStart = lastNode.next;
            tempEnd.next = lastNode;
            ListNode firstNode = tempHead.next.next;

            if (firstNode.next != null) {
                tempHead.next.next = lastNode;
                for (int j = k - 1; j > 0; --j) {
                    ListNode n = getNextNode(firstNode, j - 1);
                    tempEnd.next.next = n;
                    tempEnd.next = tempEnd.next.next;
                }

                tempHead.next = firstNode;
                firstNode.next = theNextStart;

            } else {
                break;
            }
            lastNode = getNextNode(tempHead, k + 1);
        }

        return resultHead.next;        
    }
        
    public ListNode getNextNode(ListNode head, int n) {
        ListNode result = new ListNode(0);
        result.next = head;

        for (int i = 0; i < n; ++i) {
            result.next = result.next.next;
            if (result.next == null) {
                return null;
            }
        }
        return result.next;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值