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来自键盘)。我是箭头的新手所以我无法理解它是如何做到的。
答案 0 :(得分:4)
假设您的结构有elem
和next
当你在中间插入一个新元素时,你需要做的是
+------+-------+ +-------+-------+
| | | | | |
| | | | | |
| 1 | +------------>| 2 | +------------>
| | | | | |
+------ -------+ +------- -------+
elem next elem next
+------+-------+ +-------+-------+
| | | | | |
| | | | | |
| 1 | +-------+ +------------>| 2 | +------------>
| | | | | | | |
+------ -------+ | | +------- -------+
elem next | | elem next
| +-------+----|---+
| | | | |
| | | | |
| | 3 | | |
+-->| | + |
| | |
+------- --------+
首先,您需要遍历要插入新块的块。说k
是1
您需要保存此块的next
的值。
您创建一个新块并将此next
分配给新块的next
。
新块之前的块的next
将具有新块的地址