论坛首页 编程语言技术论坛

[Leetcode] Reverse Nodes in k-Group

浏览 1131 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-08-14  
Reverse Nodes in k-GroupFeb 16 '123953 / 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;
    }
};	

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics