# 链表以k个一组进行翻转（2014美团研发笔试）

580人阅读 评论(0)

ListNode *reverseKGroup(ListNode *head, int k)
{
if (head == nullptr || head->next == nullptr || k < 2)
for (int i = 0; i < k; ++i)
{
if (next_group)
next_group = next_group->next;
else
}
// next_group is the head of next group
// new_next_group is the new head of next group after reversion
ListNode *new_next_group = reverseKGroup(next_group, k);
ListNode *prev = NULL, *cur = head;
while (cur != next_group)
{
ListNode *next = cur->next;
cur->next = prev ? prev : new_next_group;
prev = cur;
cur = next;
}
return prev; // prev will be the new head of this group
}


/* Reverses the linked list in groups of size k and returns the
pointer to the new head node. */
struct node *reverse (struct node *head, int k)
{
struct node* next;
struct node* prev = NULL;
int count = 0;

/*reverse first k nodes of the linked list */
while (current != NULL && count < k)
{
next  = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}

/* next is now a pointer to (k+1)th node
Recursively call for the list starting from current.
And make rest of the list as next of first node */
if(next !=  NULL)
{
}

/* prev is new head of the input list */
return prev;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：136558次
• 积分：2780
• 等级：
• 排名：第12968名
• 原创：134篇
• 转载：106篇
• 译文：1篇
• 评论：6条
阅读排行
评论排行