题目描述:
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) {
int n=getLength(head);
if (n<k) return head;
ListNode* begin = head;
ListNode* end = head;
ListNode* result;
while (end != NULL)
{
int count = k;
while (end != NULL&&count>0)
{
end = end->next;
count--;
}
if (count == 0)
{
result=reverseKNode(begin, end);
begin->next = reverseKGroup(end, k);
begin = end;
}
if(getLength(result)==n) return result;
}
}
int getLength(ListNode* head)
{
if (head == NULL) return 0;
int length = 0;
while (head != NULL)
{
head = head->next;
length++;
}
return length;
}
ListNode* reverseKNode(ListNode* &begin, ListNode* &end)
{
if (begin == end) return NULL;
else if (begin->next == end) return begin;
ListNode* result = new ListNode(0);
result->next = begin;
while (begin->next != end)
{
ListNode* p = begin->next;
ListNode* q = begin->next->next;
ListNode* temp = result->next;
result->next = p;
p->next = temp;
begin->next = q;
}
return result->next;
}
};

本文介绍了一种算法,该算法将链表中的节点每K个一组进行翻转,并返回修改后的链表。通过递归方法实现,不改变节点值,仅调整节点位置,并且只使用常数级额外内存。
885

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



