zoukankan      html  css  js  c++  java
  • 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.

    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

    按一定数量反转链表,可以直接用反转整个链表的办法局部反转,直接反转整个链表是使用三个指针操作一下就可以,因此只需要分出要反转的部分来处理然后调整一下前驱和后继。代码:

     1     ListNode *reverseKGroup(ListNode *head, int k) {
     2         if(k<2) return head;
     3         int i=k,j=0;
     4         ListNode* curHead,*p,*q,*t,*prev;
     5         curHead=p=head;
     6         q=p;
     7         while(q){
     8             if(i<=1){
     9                 t=q->next;
    10                 reverse(p,q);
    11                 q->next=t;
    12                 if(prev){
    13                     prev->next=p;
    14                 }
    15                 prev=q;
    16                 
    17                 if(!j){
    18                     curHead=p;
    19                     j=1;
    20                 } 
    21                     
    22                 i=k;
    23                 q=p=t;
    24             }
    25             else{
    26                 q=q->next;
    27                 i--;
    28             }
    29         }
    30         return curHead;
    31     }
    32     ListNode *reverse(ListNode*& head,ListNode*& tail){
    33         ListNode* t,*p,*prev,*q;
    34         prev=NULL;
    35         t=p=head;
    36         q=head->next;
    37         while(prev!=tail){
    38             p->next = prev;
    39             prev=p;
    40             p=q;
    41             if(q)
    42                 q=q->next;
    43         }
    44         head=prev;
    45         tail = t;
    46     }
  • 相关阅读:
    v-date
    文字在图片上
    v-生命周期
    彭博接口分类
    如何指定vim 的查找是从上往下还是从下往上[z]
    查看linux版本
    git web找不到new project解决方法
    比特币运行原理[z]
    [Z]haproxy+keepalived高可用群集
    blockchain good article
  • 原文地址:https://www.cnblogs.com/mike442144/p/3463005.html
Copyright © 2011-2022 走看看