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的倍数个节点的时候为需要逆转片段的结束位置,下一个节点为下一次需要逆转片段的起始位置。建立起始位置到结束位置的逆向链表,并与总链表连接即可。
注意:如果最后一个节点不属于结束标记,则从记录的起始位置开始直接连接到总链表即可。
1 class Solution 2 { 3 public: 4 ListNode *reverseKGroup(ListNode *head, int k) 5 { 6 ListNode *ptr = head, *s_ptr = head, *e_ptr = NULL; 7 ListNode *ret = NULL, *temp = NULL; 8 ListNode *t_head = NULL, *t_ptr = NULL, *t_end = NULL; 9 10 int count = 1; 11 while(ptr != NULL) 12 { 13 if(count%k == 0) 14 { 15 e_ptr = ptr; 16 ptr = ptr->next; 17 e_ptr->next = NULL; 18 19 t_end = s_ptr; 20 while(s_ptr) 21 { 22 if(t_head == NULL) 23 { 24 t_head = s_ptr; 25 s_ptr = s_ptr->next; 26 t_head->next = NULL; 27 t_ptr = t_head; 28 } 29 else 30 { 31 t_head = s_ptr; 32 s_ptr = s_ptr->next; 33 t_head->next = NULL; 34 t_head->next = t_ptr; 35 t_ptr = t_head; 36 } 37 } 38 t_end->next = NULL; 39 40 if(ret == NULL) 41 { 42 ret = t_head; 43 temp = t_end; 44 } 45 else 46 { 47 temp->next = t_head; 48 temp = t_end; 49 } 50 51 t_head = NULL; 52 t_end = NULL; 53 t_ptr = NULL; 54 s_ptr = ptr; 55 } 56 else 57 { 58 ptr = ptr->next; 59 if(ptr == NULL) 60 { 61 if(ret == NULL) 62 ret = s_ptr; 63 else 64 temp->next = s_ptr; 65 } 66 } 67 count++; 68 } 69 70 return ret; 71 } 72 };