zoukankan      html  css  js  c++  java
  • 环链表转单链表

        昨儿晚去笔了家公司,然后看到一个环链表转单链表的题。题是这样的,有个环链表,依次把第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;
    }
  • 相关阅读:
    jchdl
    jchdl进展
    Verilog缺少一个复合数据类型,如C语言中的结构体
    jchdl-GSL-实例
    硬件建模-几个观点
    非阻塞赋值(Non-blocking Assignment)是个伪需求
    jchdl
    jchdl
    HDU 2686 (双线程) Matrix
    LA 3602 DNA Consensus String
  • 原文地址:https://www.cnblogs.com/codingmylife/p/2684128.html
Copyright © 2011-2022 走看看