給定一個鏈表,在一定時間內反轉這個鏈表的結點,並返回修改後的鏈表。
如果結點數不是K的倍數,那麼剩余的結點就保持原樣。
你不應該在結點上修改它的值,只有結點自身可以修改。
只允許使用常量空間。
例如
給定鏈表: 1->2->3->4->5
對於 k = 2,你應該返回: 2->1->4->3->5
對於 k = 3,你應該返回: 3->2->1->4->5
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
下面的代碼並不是我的,雖然我想的差不多,但就是這個差不多導致結果的差異性……
任重而道遠啊!
/**
* 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) {
auto node = head;
for(int i = 0; i < k; ++ i) {
if(!node) return head;
node = node->next;
}
auto new_head = reverse(head, node);
head->next = reverseKGroup(node, k);
return new_head;
}
ListNode* reverse(ListNode* start, ListNode* end) {
ListNode* head = end;
while(start != end) {
auto temp = start->next;
start->next = head;
head = start;
start = temp;
}
return head;
}
};