One Code 25. A set of K flipped linked lists every day

insert image description here
The code idea
is to flip a group of K, then find a way to put K nodes in a group.
Define three pointers:
locate locates the last one of the k nodes to be flipped, that is, the first one after flipping.
The last one after the now positioning is flipped is the current first one.
Last locates the previous node of the k nodes, which is convenient for insertion operations.
In this way, we can easily flip through these three positioning pointers.
See the code comments for details.
Hand drawing warning!
insert image description here
The result is ok.
insert image description here

Specific code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* del(ListNode* pre){
    
    
        //删除pre的下一个节点并返回删除节点
        ListNode* node = pre->next;
        pre->next=node->next;
        node->next=NULL;
        return node;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
    
    
        //每k个一组翻转,通过指针定位,实现判断翻转完成及下一组的开始位置
        ListNode *dummy=new ListNode(-1);
        dummy->next=head;
        //locate定位要翻转的k节点个中最后一个,也就是翻转后的第一个。now定位翻转后的最后一个也就是当前的第一个,last定位的是这k个节点的前一个节点,方便插入操作。
        ListNode *locate=dummy,*last=dummy,*now=dummy->next;
        while(now){
    
    
            int x=0;
            while(x!=k){
    
        //找到locate该定位的位置
                locate=locate->next;
                x++;
                if(!locate) return dummy->next; //找到NULL,剩下的数不足k个,直接返回即可。
            }
            while(last->next!=locate){
    
              //翻转操作,将每个删除的节点放在locate后面
                ListNode *node = del(last);
                node->next=locate->next;
                locate->next=node;
            }
            locate=now;                         //更新这三个定位指针
            last=now;
            now=last->next;
        }
        return dummy->next;
    }
};

Guess you like

Origin blog.csdn.net/qq_41746268/article/details/108171244