首页 > 其他 > 详细

leetcode problem: Reverse Nodes in k-Group

时间:2018-02-04 00:09:32      阅读:239      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (k <= 0){
            return head;
        }
        ListNode ret = head;
        ListNode current = head;
        ListNode pre = null;
        while (true){
            ListNode testHead = current;
            boolean valid = true;
            for (int i = 0; i < k; ++i){
                if (testHead == null){
                    valid = false;
                    break;
                }
                if (i + 1 != k) {
                    testHead = testHead.next;
                }
            }
            if (!valid){
                break;
            }
            if (pre == null){
                pre = testHead;
                ret = pre;
            }
            else {
                pre.next = testHead;
            }
            ListNode oldPre = current;
            ListNode next = current.next;
            current.next = testHead.next;
            pre = current;
            current = next;
            for (int i = 1; i < k; ++i){
                ListNode n = current.next;
                current.next = pre;
                pre = current;
                current = n;
            }
            pre = oldPre;
        }
        if (pre == null){
            return head;
        }
        else {
            return ret;
        }
    }
}

 

leetcode problem: Reverse Nodes in k-Group

原文:https://www.cnblogs.com/nosaferyao/p/8411080.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!