码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode problem: Reverse Nodes in k-Group

时间:2018-02-04 00:30:38      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:reverse   tno   lin   init   div   head   for   gpo   public   

/**
 * 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

标签:reverse   tno   lin   init   div   head   for   gpo   public   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!