首页 > 代码库 > Leetcode: Reverse Nodes in k-Group

Leetcode: 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.

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个node为一组做reverse,时间复杂度O(n), 空间复杂度O(1).

class Solution {public:    ListNode *reverseKGroup(ListNode *head, int k) {        if(head == NULL || head->next == NULL || k == 0 || k == 1) return head;                ListNode *dummy = new ListNode(-1);        dummy->next = head;                ListNode *pre_f = dummy, *first = head, *second = head, *post_s = head->next;                while(first){            int c = 0;            while(second && c < k-1){                second = second->next;                post_s = second?second->next:NULL;                c++;            }            if(second){//c == k-1                second->next = NULL;                pre_f->next = reverse(first);                first->next = post_s;                                pre_f = first;                first = post_s;                second = post_s;            }else break;        }                return dummy->next;    }        ListNode * reverse(ListNode * head){        if(head == NULL || head->next == NULL) return head;                ListNode *dummy = new ListNode(-1);        dummy->next = head;                ListNode *p = head;        while(p->next){            ListNode *tmp = p->next;            p->next = p->next->next;            tmp->next = dummy->next;            dummy->next = tmp;        }                return dummy->next;    }};

 

Leetcode: Reverse Nodes in k-Group