1. topic
2. answers
- Firstly, the summary points of the linked list are determined by the fast and slow pointers.
- When there are even nodes, the number of nodes is equal to i* 2.
- When there are odd nodes, the number of nodes is equal to i* 2 + 1.
- Then each K nodes of the linked list are divided into a group. Loop to sublist for each group Flip And they are stitched together in turn.
- Finally, the redundant nodes are spliced at the end of the new list.
- The code is as follows
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { if (head == NULL || head->next == NULL || k == 1) //An empty list or only one node or k=1 is returned directly without flipping { return head; } else { int node_num = 0; // Number of nodes in linked list ListNode* slow = head; ListNode* fast = head; // Determining the Total Number of Nodes in Link List by Fast and Slow Pointer while(fast && fast->next) { slow = slow->next; fast = fast->next->next; node_num++; } if (fast) // Odd number of nodes { node_num = node_num * 2 + 1; } else // Even Nodes { node_num = node_num * 2; } int reverse_time = node_num / k; // Number of times a linked list needs to be flipped // Link list nodes less than k, do not need to flip the list if (reverse_time == 0) { return head; } else { ListNode* temp = head; // Save the header node of the linked list ListNode* tail = head; // The End of the Flipped Sublist ListNode* p1 = head; ListNode* p2 = head; ListNode* p3 = NULL; for (int i = 0; i < reverse_time; i++) { p2 = p2->next; // Make k-1 flip for (int j = 0; j < k-1; j++) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } if (i == 0) { temp = p1; // In the first round of flip, temp points to the head node of the flipped new list. } else { tail->next = p1; // Connect the flipped sub-linked list } tail = head; // Point to the end of the flipped new list head = p2; // Point back to the first node of the list to be flipped p1 = p2; } tail->next = head; // Connect redundant nodes return temp; } } } };
For more excitement, please pay attention to "seniusen".