[LeetCode] Reverse Nodes in k-Group

一题一句:
经典题目,在reverse 方程中,重点理解  prev-> (head->cur----------)->end的关系,注意此处end不在k个node中。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null){
            return head;
        }
        int count = 0;
        ListNode guard = new ListNode(0);
        guard.next = head;
        ListNode prev = guard;
        ListNode cur = head;
        while(cur != null){
            count ++;
            ListNode next = cur.next;
            if(count == k){

                prev = reverse(prev,next);
                count = 0;
            }
            cur = next;
        }
        return guard.next;
        
    }
    public ListNode reverse(ListNode prev,ListNode end){
        if(prev == null || prev.next == null){
            return prev;
        }
        ListNode head = prev.next;
        ListNode cur = head.next;
        while(cur != end){
            ListNode next = cur.next;
            cur.next = prev.next;
            prev.next = cur;
            cur = next;
        }
        head.next = end;
        return head;
    }    
}
//other way 
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || k==1)
            return head;
        ListNode node = head;
        int count = 0;
        while(node != null){
            node = node.next;
            count ++;
        }
        if(count < k)
            return head;
        int times = count/k;
        ListNode guard = new ListNode(0);
        guard.next =head;
        ListNode prev = guard;
        ListNode cur = head;
        ListNode nxt = head.next;
        
        for(int i=1; i<=times; i++){
            
            for(int j=1 ; j<=k-1; j++){
                ListNode temp = nxt.next;
                nxt.next = cur;
                cur = nxt;
                nxt = temp;
            }
            ListNode temp2 = prev.next;
            prev.next.next = nxt;
            prev.next = cur;
            
            if(i == times)//if(cur == null)
                break;
            prev = temp2;
            cur = temp2.next;
            nxt = cur.next;

        }
        return guard.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值