【LeetCode】25. Reverse Nodes in k-Group

时间:2022-05-11 23:43:07

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

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

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
if(head==NULL) return NULL;
if(==k) return head;
struct ListNode*ph=head;
struct ListNode*tmp1,*tmp2,*rear,*backup;
tmp1=NULL;
tmp2=NULL;
int i;
for(i=;i<k-&&ph->next!=NULL;i++){
ph=ph->next;
}
rear=ph;
backup=ph->next;
if(i!=k-)
return head;
ph = head;
i=k;
while(i>){
tmp2=ph->next;
ph->next=tmp1;
tmp1=ph;
ph=tmp2;
i--;
}
head->next=reverseKGroup(backup,k);
return rear;
}