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


解題:

暴力,注意邊緣


代碼:

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(k == 1 || head == NULL) return head;
        ListNode *preHead = new ListNode(-1);
        preHead->next = head;
        ListNode *pre = preHead, *now = head;
        while(1) {
            bool flag = 0;
            int i;
            ListNode *tmp = now;
            for(i = 0; i < k; i ++) {
                if(tmp == NULL) {
                    flag = 1;
                    break ;
                }
                tmp = tmp->next;
            }
            if(flag || i < k) break;
            tmp = now;
            now = now->next;
            ListNode *recNx = now->next;
            for(int i = 1; i < k; i ++, tmp = now, now = recNx, recNx = recNx->next) {
                now->next = tmp;
                if(recNx == NULL) {
                    tmp = now;
                    now = recNx;
                    break;
                }
            }
            ListNode *t = pre->next;
            pre->next->next = now;
            pre->next = tmp;
            pre = t;
        }
        return preHead->next;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章