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
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *psave= head;
ListNode *first = head;
ListNode *end = head;
ListNode *temp = NULL;
ListNode *lastfirst = head;
while(1)
{
for(int i=0;i<k-1 && NULL != end;i++)
{
end = end->next;
}
if(end == NULL) {break;}
while(first != end)
{
temp = first->next;
first->next = end->next;
end->next = first;
first = temp;
}
if(head == lastfirst) head = first;
else psave->next = first;
psave = lastfirst;
first = end = lastfirst = lastfirst->next;
}
return head;
}
};
本文介绍了一种算法,用于每K个一组反转链表节点,并返回修改后的链表。该方法不改变节点值,仅调整节点顺序,并且只使用常数内存。通过实例展示了不同K值下链表的变化。
854

被折叠的 条评论
为什么被折叠?



