我需要在列表的開頭插入一個節點,我該怎麼做?在列表的開頭插入節點
與此代碼:
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