day5--链表中的节点每k个一组翻转

首先创建了一个名为dummy的虚拟头节点,将它的next指针指向原链表的头节点。

然后,我们使用三个指针precurnex来进行翻转操作:

先计算出链表的长度,然后每次翻转k个节点,直到链表中剩余的节点不足k个为止。

在翻转过程中,使用一个循环来交换相邻的两个节点,直到完成翻转。

最后,我们返回虚拟头节点的next指针,即为翻转后的链表头指针。

#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == NULL || k == 1) {
            return head;
        }
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *pre = dummy, *cur = head, *nex = NULL;
        int len = 0;
        while (head != NULL) {
            len++;
            head = head->next;
        }
        while (len >= k) {
            cur = pre->next;
            nex = cur->next;
            for (int i = 1; i < k; i++) {
                cur->next = nex->next;
                nex->next = pre->next;
                pre->next = nex;
                nex = cur->next;
            }
            pre = cur;
            len -= k;
        }
        return dummy->next;
    }
};
int main() {
    ListNode *head = new ListNode(1);
    head->next = new ListNode(2);
    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(4);
    head->next->next->next->next = new ListNode(5);
    Solution solution;
    ListNode *result = solution.reverseKGroup(head, 2);
    while (result != NULL) {
        cout << result->val << " ";
        result = result->next;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_54809548/article/details/130850388