【leetcode】25. Reverse Nodes in k-Group 链表按K分段逆序

1. 题目

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

2. 思路

递归。
找到前K个,进行逆序。
对后面的进行递归,然后将前面链接到递归的返回结果上去。

3. 代码

耗时:19ms

/**
 * 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 == NULL || k <= 1) { return head; }
        ListNode* pl = head; // this K segment's last node
        int s = k - 1;
        while (s > 0 && pl != NULL) {
            pl = pl->next;
            s--;
        }
        if (pl == NULL) {
            return head;
        }
        ListNode* p2 = reverseKGroup(pl->next, k);
        reverse(head, pl);
        head->next = p2;
        return pl;
    }
    
    // reverse pf->...->pl, return end point pf
    ListNode* reverse(ListNode* pf, ListNode* pl) {
        if (pf == NULL || pl == NULL) { return NULL; }
        if (pf == pl) return pf;
        ListNode* p = reverse(pf->next, pl);
        p->next = pf;
        pf->next = NULL;
        return pf;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007277419
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞