[LintCode] Reverse Nodes in k-Group

发布时间:2019-06-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LintCode] Reverse Nodes in k-Group脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.

Example

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Solution

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        int i = 1;
        while (head != null) {
            if (i%k != 0) {
                head = head.next;
            } else {
                pre = reverse(pre, head.next);
                head = pre.next;
            }
            i++;
        }
        return dummy.next;
    }
    
    private ListNode reverse(ListNode pre, ListNode after) {
        ListNode cur = pre.next, next = pre.next.next;
        while (next != after) {
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
            next = cur.next;
        }
        return cur;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LintCode] Reverse Nodes in k-Group全部内容,希望文章能够帮你解决[LintCode] Reverse Nodes in k-Group所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: