[LeetCode-Algorithms-25] "Reverse Nodes in k-Group" (2017.9.28-WEEK4)

来源:互联网 发布:禄宏微交易 知乎 编辑:程序博客网 时间:2024/06/08 20:02

题目链接: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


(1)思路:申请链表,从头找到k个节点,然后循环反向链接这些节点到原有链表上,继续递归逆转后续节点,直至链表结束或者最后不满足k个节点。

(2)代码:

class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k){    ListNode*curr;    curr = head;    int count = 0;    while(curr != NULL && count != k){         curr = curr->next;        count++;    }    if (count == k) {         curr = reverseKGroup(curr, k);         while (count-- > 0) {             ListNode*tmp = head->next;             head->next = curr;             curr = head;             head = tmp;         }        head = curr;    }    return head;}}; 

(3)提交结果:

这里写图片描述

原创粉丝点击