Title Link: https://leetcode.com/problems/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, and only nodes itself is 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
/** * Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *}; */struct listnode* reversekgroup (struct listnode* head, int k) {if (k <= 1) return head;struct listnode* dummy = (struct ListNode *) malloc (sizeof (struct listnode));d Ummy->next = head;struct listnode* reversedrear = dummy;// Record the tail node of the reversed list int len = 0;while (reversedrear = reversedrear->next)//temporarily used to calculate the length of the linked list ++len;reversedrear = dummy;// Recover record after calculation of the length of a list of the tail node if (k > Len) {//If Len is less than one processing segment (k), do not need to reverse free (dummy); return head;} int pass = len/k;//a pass segment needs to be reversed, each reversal of a struct ListNode *p, *q, *r;//Three pointers for the list reversal, marking the previous, current, and next node to process the pointer while (pass--) {//per-trip inverse Goto k node p = head;q = p->next;for (int i = 1; i < K; ++i) {//reverses the direction of the current processing segment to r = Q->next;q->next = p;//reversal pointer p = q;q = R;} Reversedrear->next = p;//to connect the current processing segment to the tail of the reversed list head->next = q; Connect the current processing to the unhandled list reversedrear = head;//Update the tail of the reversed list head = head->next;//update the unhandled bracelet header}reversedrear->next = head;// Connect the remaining unhappy K node list directly to the inverted list tail head = Dummy-> Next;free (dummy); return head;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
#25 Reverse Nodes in K-group