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
//运行时间:<span style="font-family:Helvetica Neue, Helvetica, Arial, sans-serif;color:#333333;"><span style="font-size: 14px; line-height: 20px; background-color: rgb(249, 249, 249);">38ms</span></span>
class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { if (!head) return NULL; if (k<=1) return head; ListNode *ans = NULL; ListNode *ans_p = head; ListNode *p = head;//前进! ListNode *p1; ListNode *q = head; ListNode *x; ListNode *y; int count ; while (1){ count = 0; p1 = p; while (p&&count < k){ count++; p = p->next; } if (count < k) { if (!ans) ans = p1; else{ ans_p->next = p1; } break; } else{ x = y = q->next; count = 1; while (count < k){ x = x->next; y->next = q; q = y; y = x; count++; } if (!ans) { ans = q; ans_p = p1; } else { ans_p->next = q; ans_p = p1; } q = p; } if (!p) break; } return ans; } };
leetcode025:Reverse Nodes in k-Group
原文地址:http://blog.csdn.net/barry283049/article/details/45073837