leetcode:Reverse Nodes in k-Group

本文介绍了一种算法,用于在保持节点值不变的情况下,批量反转链表中连续K个节点。通过此方法,可以有效地操作链表结构,特别适用于需要对节点进行周期性操作的场景。

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个翻转后节点的头节点指针和尾节点指针。
C++代码

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode*p,*q1=head,*lastNode=head,*q2,*last;
        if (!head||k==0)
            return head;
        q2 = nodeAfterKNodes(q1, k);
        head = reverseList(q1, k, last);
        lastNode = last;
        q1 = q2;
        while (q1){ 
            q2 = nodeAfterKNodes(q1, k);
            lastNode->next= reverseList(q1, k, last);
            lastNode = last;
            q1 = q2;
        }
        return head;
    }
    ListNode* reverseList(ListNode* head,int k,ListNode*& last){
        if (!head || k > length(head)){
            last = head;
            return head;
        }   
        ListNode* p = head, *q=NULL, *r=NULL;
        last = head;
        p = head;
        q = head->next;
        head->next = NULL;
        if (q)
            r = q->next;
        int i = 0;
        while (q && i<k-1){
            q->next = p;
            p = q;
            q = r;
            if (r)
                r = r->next;
            i++;
        }
        return p;
    }
    int length(ListNode* head){
        int len = 0;
        while (head){
            len++;
            head = head->next;
        }
        return len;
    }
    ListNode* nodeAfterKNodes(ListNode* head, int k){
        if (k > length(head))
            return NULL;
        int i = 0;
        while (i < k){
            head = head->next;
            i++;
        }
        return head;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值