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;
        }
    };
  • 相关阅读:
    基本HAL库操作函数整理
    oled(iic协议)
    Uart串口中断收发
    博主回来啦
    博主的冒泡1
    AFO

    起床困难综合症
    费解的开关
    数独
  • 原文地址:https://www.cnblogs.com/winscoder/p/3407823.html
Copyright © 2011-2022 走看看