LeetCode题解——Reverse Nodes in k-Group

来源:互联网 发布:淘宝商品曝光量在哪看 编辑:程序博客网 时间:2024/06/06 07:04

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

思路很简单,第一步判断这条链的长度是否是大于k的,如果不是,则直接返回。

若是,翻转前面的k个元素,在对剩余的链做reversKgroup的递归调用,最后将这些链拼接起来

/** * 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* curr = head;        int count = 0;        while(count!=k && curr!=NULL)//find the K+1 Node        {            curr=curr->next;            count++;        }        if(count!=k) return head;                curr = reverseKGroup(curr,k);        ListNode *next;        while(count>0)        {          next = head->next;          head->next = curr;                    curr = head;          head = next;                    count--;        }            return curr;    }        ListNode* reversLinkedList(ListNode* head){        ListNode* previous = NULL;        ListNode* next = NULL;        while(head!=NULL){            next = head->next;            head->next = previous;                    previous = head;            head = next;        }        return previous;    }};


0 0