Tuesday, November 25, 2014

Reverse Nodes in k-Group

    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode dummy(0);dummy.next=head;
        ListNode*cur=head,*prev=&dummy;
        ListNode*nextsec=head;//start of next group
        while(cur){
            int tmp=k;
            while(nextsec&&tmp-->0)
                nextsec=nextsec->next;
            if(tmp>0)
                return dummy.next;
            while(cur->next!=nextsec){
                ListNode*tnode=cur->next;
                cur->next=tnode->next;
                tnode->next=prev->next;
                prev->next=tnode;
            }
            prev=cur;
            cur=nextsec;
        }
        return dummy.next;
    }


//another flavor, from anniekim

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if (k <= 1) return head;
        int reverseTimes = GetLength(head) / k;
        ListNode dummy(0); dummy.next = head;
        ListNode *ins = &dummy, *cur = ins->next;
        while (reverseTimes--)
        {
            for (int i = 0; i < k - 1; ++i) {
                ListNode *move = cur->next;
                cur->next = move->next;
                move->next = ins->next;
                ins->next = move;
            }
            ins = cur;
            cur = ins->next;
        }
        return dummy.next;
    }

    int GetLength(ListNode *head) {
        int length = 0;
        while (head) {
            head = head->next;
            length++;
        }
        return length;
    }
};

No comments:

Post a Comment