我需要在列表的开头插入一个节点,我该怎么做?在列表的开头插入节点
与此代码:
while(tmp!=NULL){
printf("__________");
printf("\nCodigo: %d\n",tmp->code);
printf("Nombre: %s\n",tmp->name);
printf("Apellido: %s\n",tmp->last);
tmp = tmp->next;
};
我打印的清单,这是我所看到的:
Codigo:3
农布雷:第三
Apellido:节点
Codigo:2
农布雷:SECC
Apellido:节点
Codigo:1
农布雷:第一
Apellido:节点
所以,如果我插入在beginnig东西我应该看到
Codigo:3
农布雷:第三
Apellido:节点
Codigo:2
农布雷:SECC
Apellido:节点
Codigo:1
农布雷:第一
Apellido:节点
Codigo:4
农布雷:第四
Apellido:节点
如何做呢?我试着用这样的:
tmp_aux = lista;// creating an aux list
while(tmp_aux->next!=NULL){
tmp_aux->next = tmp_aux;
}; // i used this becouse the last printed (up) is the first node
new_aux = (struct nodo*) malloc(1*sizeof(struct nodo));
printf("ingrese el codigo: ");
scanf("%d",&(*new_aux).code);
printf("ingrese el nombre: ");
scanf("%s",&(*new_aux).name);
printf("ingrese el apellido: ");
scanf("%s",&(*new_aux).last);
new_aux->next = tmp_aux;// then i put the aux on the next of my new node
lista = new_aux;// and make my list the new one
假设'tmp_aux'在循环开始时非空,它永远不会终止; 'tmp_aux-> next = tmp_aux'不会遍历列表,只是不断重新赋值。也许你想做'tmp_aux = tmp_aux-> next'? –
我试过,但仍然在列表底部打印第一个节点;我认为我扫描的最后一个节点应该在底部......是吗? –
你的例子显示在列表的末尾插入的不是开头。如果是在开始时,新节点会首先打印不最后的权利?那么你真的想要哪个 - 列表的开始还是结束? – kaylum