【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个节点

思路:其实和旋转整个链表的思路一样,只不过多了一个递归

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* reverseKGroup(struct ListNode* head, int k) {
 9     if(head==NULL) return NULL;
10     if(1==k) return head;
11     struct ListNode*ph=head;
12     struct ListNode*tmp1,*tmp2,*rear,*backup;
13     tmp1=NULL;
14     tmp2=NULL;
15     int i;
16     for(i=0;i<k-1&&ph->next!=NULL;i++){
17         ph=ph->next;
18     }
19     rear=ph;
20     backup=ph->next;
21     if(i!=k-1)
22         return head;
23     ph = head;
24     i=k;
25     while(i>0){
26         tmp2=ph->next;
27         ph->next=tmp1;
28         tmp1=ph;
29         ph=tmp2;
30         i--;
31     }
32     head->next=reverseKGroup(backup,k);
33     return rear;
34 }
原文地址:https://www.cnblogs.com/fcyworld/p/6283427.html