问题: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->5Subscribe to see which companies asked this question.
ListNode* reverseKGroup(ListNode* head, int k){
ListNode * newList = NULL;
ListNode * pre = head,*first = NULL,*second = newList;
int *temp = new int[k];
int i = 0;
while(pre){//判断链表是否为空
first = pre;
while(i < k && first){//判断剩余链表长度是否满足k,并将这些链表的值暂存在数组中
temp[i] = first->val;
first = first->next;
i++;
}
if (i = k){//当剩余链表长度大于等于k时
while (i > 0){//将暂存的k个数颠倒顺序加在新链表后,并pre指向剩余链表的第一节
second = new ListNode(temp[i-1]);
second = second->next;
pre = pre->next;
i--;
}
}
else{//剩余链表长度不足k时,跳出循环
break;
}
}
while (pre){//将剩余的不足k个的链表加在新链表后
second = second->next;
second = new ListNode(pre->val);
pre = pre->next;
}
return newList;//返回新的链表
}
问题: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