题目:
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.
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
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
描述:
给出一个链表和一个整数k(k不大于链表长度),对于链表,相邻的k的元素是一组,对每组的结点顺序进行翻转,
要求空间复杂度为O(1),且不能修改结点中的数据。
分析:
考察链表的操作,算不上hard级别的题目。
每k个结点为一组,组之间为尾插法,组内采用头插法建立新链表,注意要防止断链。
后台数据中有不符合题设的测试样例:(题目说好的k不大于链表的长度呢?(k is a positive integer and is less than or equal to the length of the linked list))
[]
1
其实非要特判这种情况,只需要在group_tail首次初始化时设置为my_head 而不是head就行,但是确实是题目的后台数据有问题!虽然能AC,但是有瑕疵还是要指出来的。
代码:
/**
* 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) {
ListNode* my_head = new ListNode(0);
ListNode* group_head = my_head;
ListNode* group_tail = my_head;
while (listLength(head) >= k) {
int times = k;
group_tail = head;
while (times -- ) {//完成一组的头插逆置
ListNode* temp = head;
head = head->next;
temp->next = group_head->next;
group_head->next = temp;
}
group_head = group_tail;
}
group_tail->next = head;
return my_head->next;
}
int listLength(ListNode* head) {
ListNode* temp = head;
int result = 0;
while (temp) {
temp = temp->next;
++ result;
}
return result;
}
};