Reverse Nodes in k-Group

来源:互联网 发布:湘雅大数据 编辑:程序博客网 时间:2024/05/29 14:52

Reverse Nodes in k-Group - LeetCode

题目:
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个反转,所以就只写了把前k个元素反转的代码。
想想不会这么简单,仔细看了下题目,才发现是要把每k个元素反转。
想着要把原来的代码利用起来,于是很自然地就想到了一种递归的方法。

把k个元素当成一段,每次就处理一段。
递归函数返回当前处理的这一段的head
当前这一段的last->next就等于下一段的head(这里就可以调用递归函数)

代码

#include <iostream>#include <cstdlib>using namespace std;// 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) {        ListNode* p = head;        int count = 0;        while (p != NULL) {            count++;            p = p->next;        }        return rev(head, k, count);    }    ListNode* rev(ListNode* head, int k, int length) {        if (length < k) return head;        ListNode *last = NULL, *current = NULL, *first = head;        int t = k;        current = head;        while (t--) {            current = head;            head = head->next;            current->next = last;            last = current;        }        first->next = rev(head, k, length-k);        return current;    }};

速度比我快的两种解法也都是用了递归,基本思路是一样的。