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个一组,反序后,形成新的链表。对于最后不满K个元素,保持原来的顺序输出。所以本题可以按如下方法解:
1、建立空的新链表list1.
2、如果原链表剩余元素个数不小于K个,则取K个元素,采用头插法构建反序的临时链表,插入list1的尾部。
3、如果链表剩余元素个数小于K个,则将剩余的链表插入到list1的尾部。
代码如下:
//计算链表长度 int getListSize(ListNode* head) { int count = 0; while (head) { head = head->next; count++; } return count; } //在链表头部插入元素,返回插入后的链表头指针 ListNode* addHead(ListNode*head, ListNode*Node) { Node->next = head; return Node; } ListNode* reverseKGroup(ListNode* head, int k) { int length = getListSize(head); ListNode tmpHead(-1); ListNode *pNode = &tmpHead; while(length >= k){ ListNode* pHead = NULL; for (int i=0; i<k; i++) { ListNode*ptmpNode = head; head = head->next; ptmpNode->next = NULL; //透过头插法构建反序的临时链表 pHead = addHead(pHead, ptmpNode); } pNode->next = pHead; while(pNode->next) pNode = pNode->next; length -= k; } //将链表剩余元素插入结果链表的尾部 pNode->next = head; return tmpHead.next; }