25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

参考算法:图解k个一组翻转链表

    链表的翻转就是将当前节点的下个节点的后继节点置为当前节点。

C++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
private:
    void reverseList(ListNode* list){
        ListNode *prep = list, *next = list->next;
        prep->next = NULL;
        while(next){
            ListNode *tmp = next->next;
            next->next = prep;
            prep = next;
            next = tmp;
        }
        return ;
    }
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k == 1){
            return head;
        }
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode *prep, *next, *cur, *curhead, *curtail;
        int i = 1;
        prep = dummy, next = NULL, cur = head;
        curhead = head, curtail = NULL;
        while(cur){
            i++;
            cur = cur->next;
            if(cur && i == k){
                next = cur->next;   // 后继节点确定
                curtail = cur;      // 当前队尾节点
                curtail->next = NULL;   // 当前队尾后继节点置空,方便翻转
                reverseList(curhead);   // 翻转链表
                prep->next = curtail; // 前继节点指向k个元素中的最后一个,即翻转后的第1个
                curhead->next = next; // 先前的头结点(翻转后的尾节点)指向后继节点
                prep = curhead; // 翻转后的队尾节点(翻转前队首)为前继节点
                next = NULL;    // 后继节点置空
                cur = curhead = curhead->next; // 设置新的当前队列
                curtail = NULL;
                i = 1;
            }
        }
        return dummy->next;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值