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再判断链表能够分成几组,在每一组内进行头插法翻转。
需要特别注意的就是需要保存每一个组的头结点,因为翻转完之后,它就到了组内的末尾,然后作为下一个组的组头。
ListNode* reverseKGroup(ListNode* head, int k) { if(k == 1 || head == NULL) return head; int length = 0; ListNode* p = head; while(p!=NULL) { length++; p = p->next; } int groupNum = length/k;//组数,比如length=13,k=5,则一共2组 ListNode* dumb = new ListNode(0); dumb->next = head; p = head;//p代表当前结点 ListNode* q = p->next;//保存下一个结点 ListNode* pre = dumb;//当前结点前驱 ListNode*tempHead = pre; //tempHead为每一组的 头结点前驱 别的结点插入到它后面t empHead->1 2 3 4 5 for(int i =1;i <= groupNum;i++) { tempHead = pre; for(int j =0;j < k ;j++)// 组内 头插法翻转 { p->next = tempHead->next; tempHead->next = p; pre = p; p = q; if(q!=NULL) q = q->next; } head->next = p; pre = head; head = p;//head 现在为下一组的第一个 相当于刚开始时候的head 也就是每一组的head } pre->next = head; return dumb->next; }