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->5
代码如下:
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (k == 1) return head;
if (head == NULL) return NULL;
ListNode *front = new ListNode(0);
ListNode *h = head;
int count = 0;
ListNode *p = front; int flag = 0;
while (count<k&&h!=NULL)
{
ListNode *s = new ListNode(h->val);
s->next = front->next;
if (flag == 0) { flag = 1; p = s; }
front->next = s;
h = h->next;
++count;
}
if (count < k)
{
while (front != NULL)
{
ListNode *temp = front;
front = front->next;
delete temp;
temp = NULL;
}
return head;
}
p->next = reverseKGroup(h, k);
ListNode *temp = front;
front = front->next;
delete temp;
temp = NULL;
return front;
}
};
链表K个一组翻转
本文介绍了一种算法,该算法将链表中的节点每K个一组进行反转,并返回修改后的链表。讨论了当节点数不是K的倍数时如何处理剩余节点,并提供了实现代码。

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



