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个节点的函数,每次转换k个。注意转换函数中,由头到尾转换时候pEnd以及pHead顺序的变换。

代码:

class Solution {
//https://leetcode.com/problems/reverse-nodes-in-k-group/
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(k<=0||head==NULL)    return head;
        
        ListNode *dummy=new ListNode(0);dummy->next=head;
        ListNode *p=dummy;
        
        while(p){
            p->next=reverseList(p->next,k);
            for(int i=1;p&&i<=k;i++){
                p=p->next;
            }
        }
        return dummy->next;
    }
    
    ListNode* reverseList(ListNode* head,int k){
        if(k<=0)    return head;
        ListNode* pEnd=head; 
        while(pEnd&&k){
            pEnd=pEnd->next;
            k--;
        }
        if(k>0) return head;
        ListNode *pHead=pEnd,*p=head;
        while(p!=pEnd){
            ListNode *q=p->next;//有一个好处就是pHead指向空的,自动的了,不想之前需要考虑这个问题,直接从头部指向最后一个
            p->next=pHead;
            pHead=p;
            p=q;//从后面往前
        }
        return pHead;//连续,后面不断开
    }
};


原文地址:https://www.cnblogs.com/jsrgfjz/p/8519823.html