[LeetCode]—Reverse Nodes in k-Group 将链表以n个节点为一组进行逆序

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

注意:如果最后不足长度为K的部分,不进行逆序。

分析:其实本题主要在考察链表逆序的问题。只是将长链表分多组逆序,多了每组逆序后,向前向后链接的步骤。


class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode *p=head,*q=head;
        ListNode *ghead,*gtail,*front=NULL,*back=NULL;
       
        
        while(p!=NULL){
        int n=k-1;

        while(n--){
         if(p->next==NULL) return head;    
         p=p->next;
        }//p指向长度为k的group的tail
        
        
        ghead=q;gtail=p;
        back=p->next;
      
        if(ghead==gtail)return head;

        reverseList(ghead,gtail);
        ghead=p;gtail=q;  //逆序后,收尾交换了

        if(front==NULL){  //第一个分组
         head=ghead;
        }
        else{
        front->next=ghead;
        }
        
        front=gtail;

        gtail->next=q=p=back;
      }

        return head;
                  
    }

private:
     ListNode *reverseList(ListNode *head,ListNode *tail){
          if(head==tail)return head;  //只有一个值
          
          tail=tail->next;
          ListNode *p,*q,*temp;
          p=head;q=head->next;
          while(q!=tail){
          temp=q;
          q=q->next;
          temp->next=p;
          p=temp;
          }
          head->next=NULL;
          head=p;

          return head;
         
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值