【问题标题】:Insert and delete in a multi level sorted linked list在多级排序链表中插入和删除
【发布时间】:2021-08-09 14:20:13
【问题描述】:

2->7->8->11

|

13->16->17->21

|

22->23->27->29

|

30->32

如上所述的排序链表,其中每个节点有 2 个指针 next 和 down。对于每一行起始节点向下指向下一行开始。每行有 4 个元素,除了最后一个可以有

【问题讨论】:

  • 听起来很直接。您具体遇到了什么问题,您可以展示任何代码尝试吗?
  • 假设我要插入 9 那么首先我们必须找到要插入 9 的位置(这里它在 8 和 11 之间)然后我们必须移动所有元素,因为每个列表都可以有4 个元素,除了最后一个。所以 11 现在将移动到第二行,所以 2 的向下指针会改变。这个转换代码对我来说看起来很棘手。同样,在删除的情况下,我们必须进行类似的转换,这看起来很棘手。你能写代码吗?
  • 应该不难。在我看来,您需要两个函数 1)将最后一个元素推送到子列表,以及 2)从子列表中弹出最后一个元素,如果长度约束会被违反,则应分别在插入和删除之前调用每个元素操作。我希望这会有所帮助。
  • 如果添加 100 个值,子列表是否仍会被限制为 4 个元素,或者是否有平方根(值的总数)在这里起作用?这是有道理的,因为在许多情况下它允许在 O(sqrt(n)) 中插入和删除。
  • 或者可以递归使用下行链路,将每个列表的垂直长度限制为4?

标签: algorithm data-structures linked-list


【解决方案1】:

add操作的结构表示和伪代码如下 并且我们可以以添加数据为例,递归实现删除

typedef struct sibling{
    int data;
    struct sibling *nxt;
} t_sibling

typedef struct children {
    struct sibling  *sibling;
    struct children *nxt;
} t_children;


add_element(t_children **head, int newdata)
{
    t_children *walk_down = *head;
    t_children *parent  = NULL;
    
    while (walk_down != NULL) {
        if(parent == NULL && Compare newdata < head of current walk_down->sibling) {
            // Code comes here when we add 1 to above mentioned list example
            newdata is added to begining to head of walk_down->sibling
            sibling_list_count++;
            if (sibling_list_count > 4) {
                taildata = delete_end from tail of walk_down->sibling
                add_element(&walk_down, taildata)
            }
            break;
        }
        else if(newdata < head of current walk_down->sibling) {
        
            if (Compare newdata > tail of parent sibling) {
                // Code comes here when we add  12 to above mentioned list
                newdata is added to begining to head of walk_down->sibling
                
                if (sibling_list_count > 4) {
                    taildata = delete_end from tail of walk_down->sibling
                    add_element(&walk_down, taildata)
                }
            }
            else {
                // Code comes here when we add 6 to above mentioned list
                newdata is added to the appropriate location of parent of sibling
                Since above step disturbs the <= 4 property we 
                taildata = delete_end from tail of parent->sibling
                add_element(&walk_down, taildata)
            }
            break;
        }
            
        parent = walk_down;
        walk_down = walk_down->nxt;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2016-09-15
    • 2021-06-15
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多