zoukankan      html  css  js  c++  java
  • [leetcode-25-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.
    k is a positive integer and is less than or equal to the length of the linked 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

    思路:

    首先统计链表长度,然后根据k再判断链表能够分成几组,在每一组内进行头插法翻转。

    需要特别注意的就是需要保存每一个组的头结点,因为翻转完之后,它就到了组内的末尾,然后作为下一个组的组头。

    ListNode* reverseKGroup(ListNode* head, int k)
     {
         if(k == 1 || head == NULL) return head;
         int length = 0;
         ListNode* p = head;
         while(p!=NULL)
         {
             length++;
             p = p->next;
         }
         int groupNum = length/k;//组数,比如length=13,k=5,则一共2组
         ListNode* dumb = new ListNode(0);
         dumb->next = head;
         p = head;//p代表当前结点
         ListNode* q = p->next;//保存下一个结点
         ListNode* pre = dumb;//当前结点前驱
        ListNode*tempHead = pre; //tempHead为每一组的 头结点前驱 别的结点插入到它后面t empHead->1 2 3 4 5
         for(int i =1;i <= groupNum;i++)
         {
             tempHead = pre;
             for(int j =0;j < k ;j++)// 组内 头插法翻转
             {
                 p->next = tempHead->next;
                 tempHead->next = p;
                 pre = p;
                 p = q;
                if(q!=NULL) q = q->next;
             }
              head->next  = p;
              pre = head;
              head = p;//head 现在为下一组的第一个 相当于刚开始时候的head 也就是每一组的head
         }
         pre->next = head;
    
         return dumb->next;
    }
  • 相关阅读:
    第二十四讲 ASP.NET中开发复合控件
    第二十六讲 使用ASP.NET实现网络通讯
    第二十五讲 ASP.NET中的XML
    【经验】android webview 后退键导致表单再次提交
    【笔记】java 泛型
    【笔记】Collection
    【算法】Tween算法
    【JavaSript】发现一个漏洞
    【研究】加载图片时,同一url,多次request
    【笔记】多态之Override
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6682338.html
Copyright © 2011-2022 走看看