25. Reverse Nodes in k-Group

题目描述:给链表,每连续的k个元素变成转置,若len % k != 0,后面多余的元素保持原样。如:

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

同样要求空间复杂度为O(1),不能修改结点的值,只能改结点本身。

分析:时间复杂度O(n),空间O(1)。

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(!head ||k == 1) return head;
        
        int num=0;
        ListNode *l(-1);
        l -> next = head;
        ListNode *cur = l, *nex, *pre = l;
        
        while(cur = cur -> next) 
            num++;
        
        while(num >= k)       //每轮处理k个结点的倒置
        {
            cur = pre -> next;
            nex = cur -> next;
            for(int i = 1;i < k; i ++)        //处理1~k个结点的倒置
            {
                cur -> next = nex ->next;
                nex -> next = pre ->next;
                pre -> next = nex;
                nex = cur->next;
            }
            //重新归位三个指针,在下一轮开始前保证相对位置
            pre = cur;
            num -= k;
        }
        return l -> next;
    }
};

你可能感兴趣的:(25. Reverse Nodes in k-Group)