Reverse Nodes in k-Group

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

 

Code:

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head==NULL)  return head;
        ListNode *start=new ListNode(0);
        start->next=head;
        ListNode *p1=start; // begin
        ListNode *p2=start; // count to the end
        int n=0;
        for(int n=1;p2;n++){
            p2=p2->next;
            if(p2&&n%k==0&&k>1){
                ListNode *pre=p1->next;
                ListNode *cur=p1->next->next;
                ListNode *nex=NULL;
                p1->next=p2;
                p1=pre;
                p1->next=p2->next;
                while(cur&&cur!=p2){
                    nex=cur->next;
                    cur->next=pre;
                    pre=cur;
                    cur=nex;
                }
                cur->next=pre;
                p2=p1;
            }
        }
        head=start->next;
        delete start;
        return head;
    }
};

 

posted @ 2013-11-05 04:59  WinsCoder  阅读(140)  评论(0编辑  收藏  举报