LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)

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个就不翻转。

先统计有多少个结点,然后len/k表示要翻转多少趟。编写上要注意很多指针的变化,不小心就会出错。特别是如何修改“前k个结点翻转后的指针”的指向。我们这里定义了ListNode **Phead。当下次的k个翻转过以后的新的头指针,赋值给*Phead。就能得到拼接。同样,翻转开始时的第一个结点的next指针也是不停的要变化,我们这里也设置了ListNode **cur。

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head == NULL || k <= 1) //当k=1的时候也直接返回
            return head;
        int len = 1;    //统计有多少个结点
        ListNode *p = head;
        while(p->next){
            len++;
            p = p->next;
        }
        if(len<k || len == 1)
            return head;
        int n = len/k;  //循环多少次
        ListNode **Phead = &head;   //保存“上层k结点翻转后的最后的指针”
        p = head;
        while(n--){
            ListNode **cur = &(p->next);    //保存首个结点的指针,因为其一直变话向后指
            for(int i = 1;i < k;i++){
                ListNode *q = *cur;
                *cur = q->next;
                q->next = p;
                p = q;
            }
            *Phead = p; //“上层最后的指针”指向这一层的头指针
            Phead = cur;    //保存“这一层翻转后的最后的指针”
            p = *cur;   //指向下层的头结点
        }
        return head;
    }
};

点赞