LeetCode Reverse Nodes in k-Group

原题链接在这里:https://leetcode.com/problems/reverse-nodes-in-k-group/

思路: 1. 检测list长度,用此长度除以k,得到的就是需要roate的次数,记为rotNum,如果rotNum等于0,则不需要rotate,直接 返回head .

2. 这类内部rotate都需要标记前一个点,用以连接rotate后的那段head,这个标记记为mark。有些需要从原有list 的head开 始rotate,所以需要create一个dunmy, dunmy.next = head.

3. 内部roate时与Reverse Linked List的method 2 相同。每次tail = mark.next, cur = tail在循环中重复更新,旋转一 次,k--知道k>1(Here, there is no need to check if tail.next = null, 因为之前有rotNum的限制). 每次rotNum is decreased by one, until 0.

Note:  在生成dunmy时注意 new ListNode(0), 这部分不能省略。

AC Java:

/**
 * 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 || head.next == null || k < 2){
            return head;
        }
        int i = 0;
        ListNode tail = head;
        while(tail != null){
            i++;
            tail = tail.next;
        }
        int rotNum = i/k;
        int numK = k;
        if(rotNum == 0){
            return head;
        }
        ListNode dunmy = new ListNode(0); //error
        dunmy.next = head;
        ListNode mark = dunmy;
        
        while(rotNum>0){
            tail = mark.next;
            ListNode cur = tail;
            ListNode pre;
            ListNode temp;
            while(k > 1){
            pre = cur;
            cur = tail.next;
            temp = cur.next;
            cur.next = pre;
            tail.next = temp;
            k--;
            }
            mark.next = cur;
            mark = tail;
            tail = mark.next;
            cur = tail;
            k = numK;
            rotNum--;
        }
        return dunmy.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值