Leetcode题解-25. Reverse Nodes in k-Group

Leetcode题解-25. 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.

k is a positive integer and is less than or equal to the length of the linked 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=4时1->2->3->4变成4->3->2->1。若最后一组节点数量不够K时,保持原来顺序不变,即当K=3时1->2保持不变。

思路

由于是单向链表,所以不能两端向中间靠交换节点的值,只能进行指针操作,改变节点的位置。
两个节点进行反转顺序的时候很容易进行操作,那我们先把组内的第一二个节点反转顺序。然后把已经反转了顺序的第一二个节点看成一个节点和第三个节点进行顺序反转,如此类推直到组的结尾。每个组进行同样的操作。

示意图:
1、 1->2->3->4
2、 2->1->3->4
3、 3->2->1->4
4、 4->3->2->1

为此需要三个指针和一个不属于原链表的头-1
-1->1->2->3->4
Leetcode题解-25. Reverse Nodes in k-Group_第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;
        ListNode* prehead = new ListNode(-1);
        prehead->next = head;
        ListNode* cur = head, *next, *pre = prehead;
        int num = 0;
        //计算链表长度
        while(cur){
            num++;
            cur = cur->next;
        }
        //num < k 时保持顺序不变
        while(num >= k){
            cur = pre->next;
            next = cur->next;
            for(int i = 1; i < k; i++){
                cur->next = next->next;
                next->next = pre->next;
                pre->next = next;
                next = cur->next;
            }
            pre = cur;
            num -= k;
        }
        return prehead->next;
    }
};

你可能感兴趣的:(Leetcode)