环链表转单链表
昨儿晚去笔了家公司,然后看到一个环链表转单链表的题。题是这样的,有个环链表,依次把第m个节点删除环链表(约瑟夫环操作)。最后根据节点删除顺序重建为单向链表,并返回。
void reorder(node **head, int m)
{
// Check param.
if (head == NULL || *head == NULL || m <= 0)
{
return;
}
// Special case.
if (m == 1)
{
node *p = *head;
while (p->next != *head) p = p->next;
p->next = NULL;
return;
}
node **backup = head;
node *iter = *head, *curr = NULL, *ret = NULL;
int n = 0;
while (iter->next != iter)
{
++n;
// iter always equals *backup.
if (!(n % m))
{
if (ret == NULL)
{
ret = curr = iter;
}
else
{
curr->next = iter;
curr = curr->next;
}
// Update backup.
*backup = (*backup)->next;
}
else
{
// Update backup.
backup = &iter->next;
}
iter = iter->next;
}
// Link last node.
if (iter != curr)
{
curr->next = iter;
iter->next = NULL;
}
// Write return value.
*head = ret;
}