【LeetCode】Reverse Nodes in k-Group 解题报告

【题目】

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.

For 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

【解析】

题意:把原始链表k个k个的反转,如果最后剩余的不到k个结点,那么保持不变。

没什么特殊算法,我觉得重点在于怎么不用额外的空间反转k个结点,用三个指针 curtail, curhead, posthead,curtail 指向反转后的尾结点,curhead 指向反转后的头结点,posthead 是反转过程中 curhead 的后一个结点,用于辅助反转。这个方法可以对照题目 【LeetCode】Reverse Linked List II 解题报告 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k < 2) return head;
        
        ListNode prehead = new ListNode(0);
        prehead.next = head;
        int cnt = 0;
        ListNode node = head;       //迭代结点
        ListNode lasttail = prehead;//上次k个结点反转后的尾结点
        ListNode curtail = head;    //这次要反转的k个结点的尾结点
        ListNode curhead = head;    //这次要反转的k个结点的头结点
        ListNode posthead = null;   //这次要反转的k个结点的头结点后面的一个结点
        while (node != null) {
            cnt++;
            node = node.next;
            
            //反转这k个结点
            if (cnt == k) {
                ListNode tmp = curtail.next;
                while (tmp != node) {
                    posthead = curhead;
                    curhead = tmp;
                    tmp = tmp.next;
                    curhead.next = posthead;
                }
                lasttail.next = curhead;//把这次反转的k个结点接到上次的k个结点后
                lasttail = curtail;
                curtail = node;
                curhead = node;
                cnt = 0;
            }
            
        }
        
        //如果后面还有少于k个的结点,直接把其接到之前的链表上
        lasttail.next = curhead;
        
        return prehead.next;
    }
}


相关题目: 【LeetCode】Reverse Linked List II 解题报告 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值