C中的箭头在中间插入一个新元素

时间:2014-02-13 08:55:22

标签: c list structure

void New_list ( struct el * *start, struct el * *end )
{

    struct el *g;
    int x;
    puts (Insert elements, to finish insert 0:" );

    *start = NULL;
    *end = NULL;

    scanf("%d", &x);

    while( x != 0 )
    {
        if ( *start == NULL)
        {
            g = (struct el *) malloc(sizeof(struct el));
            g->elem = x;
            g->next = NULL;
            *end = g;
            *start = g;
        }
        else
        {
            g = (struct el *) malloc(sizeof(struct el));
            g ->elem = x;
            g ->next = NULL;
            (*end)->next = g;
            *end = g;
        }
        scanf( "%d", &x );
    }
}

我有这个列表,我需要在k元素之后插入一个新元素(k来自键盘)。我是箭头的新手所以我无法理解它是如何做到的。

1 个答案:

答案 0 :(得分:4)

假设您的结构有elemnext

当你在中间插入一个新元素时,你需要做的是

  +------+-------+         +-------+-------+
  |      |       |         |       |       |
  |      |       |         |       |       |
  |   1  |   +------------>|   2   |   +------------>
  |      |       |         |       |       |
  +------ -------+         +------- -------+
   elem    next              elem    next


  +------+-------+                                  +-------+-------+
  |      |       |                                  |       |       |
  |      |       |                                  |       |       |
  |   1  |   +-------+                +------------>|   2   |   +------------>
  |      |       |   |                |             |       |       |
  +------ -------+   |                |             +------- -------+
   elem    next      |                |               elem    next
                     |   +-------+----|---+
                     |   |       |    |   |
                     |   |       |    |   |
                     |   |   3   |    |   |
                     +-->|       |    +   |
                         |       |        |
                         +------- --------+

首先,您需要遍历要插入新块的块。说k是1

您需要保存此块的next的值。

您创建一个新块并将此next分配给新块的next

新块之前的块的next将具有新块的地址