题目描述:
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.
代码:
/**
* 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) {
if(head == NULL) return NULL;
if(k == 0) return head;
int length = 0;
ListNode* current = head;
ListNode* pre = new ListNode(0);
ListNode* result = pre;
pre -> next = head;
while(current != NULL){
length++;
current = current -> next;
}
current = head;
ListNode* pos = current -> next;
while(length >= k){
for(int i = 0; i < k - 1; i++){
current -> next = pos -> next;
pos -> next = pre -> next;
pre -> next = pos;
pos = current -> next;
}
length -= k;
pre = current;
current = current -> next;
if(current != NULL) pos = current -> next;
}
return result->next;
}
};
本题目是一个hard题,一次AC,但是有参考别人的方法。最开始自己的思路是,写一个链表反转函数, 每次从原链表中截取长度为k的链表,然后调用该函数反转,然后继续截取k个,反转,以此类推。但是后来仔细审题,发现题目要求空间复杂度必须为O(1),因此该方法就被放弃了。后来又想着每个结点和他之后的第k-1个结点互换,但是这样的话,在换的过程中会导致大量的时间复杂度,因此也被放弃。最终参考别人的思路,如下:
首先遍历一遍链表,得到链表的长度length,然后,再对链表进行遍历。k个一组进行处理,在每个小组中,分别记录一下该组的前一结点pre,然后将该组头结点之后的所有结点依次插入到pre结点后即可,其实就是用头插的方法,反转链表。最开始自己写的链表反转函数也是用同样的方法反转的,但是在之后考虑的方法中,脑子抽抽了没想到这么做记录一下就可以,难受。
静心尽力!