zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    洛谷单元最短路标准版——spfa优化
    airline
    有依赖的背包
    挖地雷
    带分数问题
    子集和问题
    循环比赛日程表
    传纸条
    机器分配
    分组背包
  • 原文地址:https://www.cnblogs.com/winscoder/p/3407823.html
Copyright © 2011-2022 走看看