[Leetcode] Reverse Nodes in k-Group

Reverse Nodes in k-Group Feb 16 '12 3953 / 13303

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

 

 

/**
 * 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) {
        if (k == 1) return head;

        ListNode *start, *end, *prev, *next, *my_head;
        start = end = head;
        my_head = new ListNode(123);
        my_head->next = head;
        prev = my_head;

        while (start != NULL) {
            int t = 1;
	        while (end != NULL && t < k) {
	        	t++;
	        	end = end->next;
	        }
	        if (t == k && end != NULL) {
	        	next = end->next;
	        	reverse(start, end, prev, next);
	  	        prev = start; 
	        	start = end = prev->next;
	        } else {
                break;   
	        }
        }

        ListNode* res = my_head->next;
        delete my_head;
        return res;
    }

    void reverse(ListNode* s, ListNode* e, ListNode* p, ListNode* n) {
    	
    	ListNode *cur = s, *prev = NULL, *next;
    	while (cur != n) {
    		next = cur->next;
    		cur->next = prev;
    		prev = cur;
            cur = next;
    	}
    	p->next = e;
    	s->next = n;
    }
};	

 

 

@2013-10-03

/**
 * 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) {
        if (head == NULL) return head;
        ListNode *s, *e, *next, *prev, myhead(99);
        myhead.next = head;
        prev = &myhead;
        s = head;
        int cnt;
        while (s != NULL) {
            cnt = 1;
            e = s;
            while (e != NULL && cnt < k) e = e->next, cnt++;
            if (cnt < k || e == NULL) break;
            next = e->next;
            reverse(s, e);
            prev->next = e;
            s->next = next;
            prev = s;
            s = next;
        }
        return myhead.next;
    }
    
    void reverse(ListNode* head, ListNode* tail) {
        ListNode* prev = NULL, *cur = head, *next;
        while (prev != tail) {
            next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        
    }
};

 

你可能感兴趣的:(LeetCode)