码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Reverse Nodes in k-Group

时间:2014-11-17 13:56:54      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   os   sp   for   div   

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

标签:des   style   blog   io   color   os   sp   for   div   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4103300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!