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     }
  • 相关阅读:
    Python列表推导式,字典推导式,元组推导式
    python装饰器@,内嵌函数,闭包
    7-route命令
    6-mv命令
    5-ln链接命令
    4-linux建立用户用户组以及新用户的赋权
    3-gzip压缩解压命令
    2-date命令
    1-cp命令
    UIViewContentMode的各种效果
  • 原文地址:https://www.cnblogs.com/mike442144/p/3463005.html
Copyright © 2011-2022 走看看