Hi I'm trying to insert an element inside a list following a certain order(I have to add a equilateral triangle). When I try to use the code I can insert data(triangle measurements) but when I try to print list nothing appear :/.So I think that I wrote bad something in "inserisciPerPerimetro". Some word is written in italian and this is only a part of the code(two functions to add a triangle in my list),if u have to see also other parts let me know.
Thanks all!
This is my code:
typedef struct punto {
int x;
int y;
} PUNTO;
typedef struct triangolo {
PUNTO v;
int lato;
} TRIANGOLO;
typedef struct nodo {
TRIANGOLO t;
struct nodo *next;
} NODO;
int perimetro(TRIANGOLO t) {
return t.lato*3;
}
void stampaTriangolo(TRIANGOLO t) {
printf("Il triangolo ha il lato uguale a: %d con un perimetro pari a %d, il vertice in alto ha coordinate (%d,%d)\n",
t.lato, perimetro(t),t.v.x,t.v.y);
}
void stampaLista(NODO *head) {
if(head->next==NULL) {
printf("Lista vuota!\n");
} else {
while(head->next != NULL) {
head = head->next;
stampaTriangolo(head->t);
}
}
}
TRIANGOLO creaTriangolo() {
TRIANGOLO nuovo;
printf("Inserisci il lato del nuovo triangolo: ");
scanf("%d", &nuovo.lato);
printf("\n");
printf("Inserisci le coordinate del vertice con y maggiore:\n");
printf("x: ");
scanf("%d",&nuovo.v.x);
printf("\n");
printf("y: ");
scanf("%d",&nuovo.v.y);
printf("\n");
return nuovo;
}
void inserisciPerPerimetro(NODO *head) {
NODO* nuovoNodo;
nuovoNodo = malloc(sizeof(NODO));
nuovoNodo->t = creaTriangolo();
nuovoNodo->next = NULL;
if(head==NULL) {
head = nuovoNodo;
} else {
//Ordinamento per perimetro crescente
while(head->next != NULL)
if(perimetro(nuovoNodo->t) < perimetro(head->t)) {
nuovoNodo->next = head->next;
head->next = nuovoNodo;
} else {
head = head->next;
}
printf("Inserimento effettuato!\n");
}
}
int main() {
/* inizializza la lista */
NODO *head = malloc(sizeof(NODO));
head->next = NULL;
int risposta = -1; // per interazione con utente
while(risposta != 0) {
/* richiedi un'operazione all'utente */
printf("Che operazione vuoi svolgere?\n");
printf("1 -> Inserisci un triangolo nella lista ordinata secondo il perimetro crescente\n");
printf("2 -> Cancella il triangolo in testa alla lista\n");
printf("3 -> Visualizza la lista di triangoli\n");
printf("0 -> Termina il programma\n");
scanf("%d", &risposta);
/* gestisci le operazioni dell'utente */
if(risposta==1) {
inserisciPerPerimetro(head);
}
//else if(risposta==2)
//lista = cancellazione(lista);
else if(risposta==3) {
stampaLista(head);
}
else if(risposta==0) {
printf("Finito!\n\n");
}
else {
printf("Selezione non valida!\n\n");
}
}
}
I'm going to assume that you're holding a NODO* in some outer scope, and calling inserisciPerPerimetro on that pointer.
If you consider just the first time you do this (when the list is empty), your code will do head = nuovoNodo; so you will be putting the address of the newly allocated node into the pointer head. But this is a local copy of the parameter that you passed to the function, so the pointer in the outer scope will remain unchanged (and its value will be NULL). The next time you call the function, the list will still be empty.
One possible way to solve this is by passing a pointer to your head pointer to the function, so that the value of the pointer in the outer scope can be modified.
That is, the function should be defined like this:
void inserisciPerPerimetro(NODO **head)
Inside the function, modifications to head should be implemented as:
*head = nuovoNodo;
And in the outer scope you should have something like:
/*...*/
NODO* head = NULL;
inserisciPerPerimetro(&head);
/*...*/
EDIT:
Note that you are somewhat inconsistent with the node allocations: The head node is allocated in the outer scope (does it ever get its own triangle?), and all the others are allocated within the function. On the other hand, you check inside the function whether head is NULL - how can that happen if you allocate the list head in the outer scope?
Secondly, note that in the first call to inserisciPerPerimetro the while loop will be skipped because head->next is always NULL. This is because you don't handle the case where the new node needs to be inserted after the last node in the list.
Related
When compiling this code, the compiler doesn't return any warnings or errors but the code simply doesn't work.
The function inserirDado is supposed to recursively create nodes and store values on them, at node.valor, applying the conditions I set before.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
* no = (struct node *) malloc(sizeof(struct node));
(*no)->direita = NULL;
(*no)->esquerda = NULL;
(*no)->valor = numero;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
At emOrdem, the functions calls itself until it reaches the leaves, then it should print the values stored at node.valor :
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%i", no->valor);
emOrdem(no->direita);
}
}
The complete code is:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int valor;
struct node *esquerda;
struct node *direita;
};
void inserirDado(struct node **no, int numero);
void emOrdem(struct node *no);
int main(void) {
struct node **arvore1;
inserirDado(arvore1, 4);
inserirDado(arvore1, 2);
inserirDado(arvore1, 3);
inserirDado(arvore1, 10);
emOrdem(*arvore1);
}
//Funcao de colocar um numero aleatoria dentro de um Node.
//Ao fazer isso com varios numeros, serao criados nodos com descendentes.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
* no = (struct node *) malloc(sizeof(struct node));
(*no)->direita = NULL;
(*no)->esquerda = NULL;
(*no)->valor = numero;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%i", no->valor);
emOrdem(no->direita);
}
}
(1) Actually you should receive SEG Fault because you haven't initialized arovore1 to NULL.
(2) The important thing to mention here is, we use double pointers to get rid of return values. And what you have done here is a bit contradicting that.
--> Basically we'll create a node (arvore1) and then send the address of the node (&arvore1)
to the insertNode (inserirDado) function and inside that, we update corresponding node in that
address to the newly created node (temp).
I have attached the working code here. Please refer this and incase any doubts you can comment them down.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int valor;
struct node *esquerda;
struct node *direita;
};
void inserirDado(struct node **no, int numero);
void emOrdem(struct node *no);
int main(void) {
struct node *arvore1 = NULL;
inserirDado(&arvore1, 4);
emOrdem(arvore1);
}
//Funcao de colocar um numero aleatoria dentro de um Node.
//Ao fazer isso com varios numeros, serao criados nodos com descendentes.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
struct node *temp = (struct node *) malloc(sizeof(struct node));
(temp)->direita = NULL;
(temp)->esquerda = NULL;
(temp)->valor = numero;
*no = temp;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%d", no->valor);
emOrdem(no->direita);
}
}
If you compile this code with GCC 10, with switches -W -Wextra -Wall (which isn't all warnings, by the way), you get:
<source>: In function 'main':
<source>:18:5: warning: 'arvore1' is used uninitialized in this function [-Wuninitialized]
18 | inserirDado(arvore1, 4);
| ^~~~~~~~~~~~~~~~~~~~~~~
GodBolt
and that shows you where the problem is: You're trying to initialize the place arvore1 is pointing to instead of initializing it.
Please also read:
Why should I always enable compiler warnings?
You must allocate buffer and assign it to arvore1 before passing that to inserirDado.
int main(void) {
struct node **arvore1 = malloc(sizeof(struct node*)); // add malloc()
inserirDado(arvore1, 4);
inserirDado(arvore1, 2);
inserirDado(arvore1, 3);
inserirDado(arvore1, 10);
emOrdem(*arvore1);
}
Another option is to change arvore1 from "a pointer to pointer" to "a pointer",
and pass pointer to that to inserirDado.
int main(void) {
struct node *arvore1 = NULL;
inserirDado(&arvore1, 4);
inserirDado(&arvore1, 2);
inserirDado(&arvore1, 3);
inserirDado(&arvore1, 10);
emOrdem(arvore1);
}
I'm trying to push an element in a linked list, then print it but the problem received is: segmentation fault.
I've created struct libro, cella and lista. Then in function insHead i've tried to insert an element to the list, taking input from user and then in function printList (and here i've got the segmentation fault) i would print list's elements.
The code is:
typedef struct libro {
char titolo[64];
char autore[32];
short inLibreria;
short fuoriLibreria;
short id;
} Libro;
typedef struct cella {
Libro libro;
struct cella *pNext;
} Cella;
typedef Cella *Pcella;
typedef struct listaLibri{
Cella *pFirst;
Cella *pLast;
} ListaLibri;
void insHead(ListaLibri lista){
Pcella cella;
Libro libro;
printf("Inserisci titolo libro: ");
scanf("%s", libro.titolo);
printf("Inserisci autore libro: ");
scanf("%s", libro.autore);
printf("Inserisci il numero di copie presenti in libreria: ");
scanf("%d",&libro.inLibreria);
if(lista.pFirst == NULL){
cella = NULL;
Pcella temp = cella;
cella = malloc(sizeof(Cella));
(*cella).libro = libro;
(*cella).pNext = temp;
lista.pFirst = cella;
lista.pLast = cella;
}
printList(lista);
}
void printList(ListaLibri *lista){
Pcella cella = lista->pFirst;
Pcella temp = cella;
while (temp != NULL){
printf("%s", temp->libro.autore);
temp = temp->pNext;
}
free(cella);
free(temp);
}
void main(){
ListaLibri lista;
insHead(lista);
}
First of all you have to initialize lista.pFirst and lista.pLast with NULL.
int main()
{
ListaLibri lista;
lista.pFirst = NULL; // <- init NULL
lista.pLast = NULL; // <- init NULL
insHead( &lista ); // <- pass pointer to list to function insHead
insHead( &lista );
.....
deleteList( &lista );
return 0;
}
The input paramter to your function insHead has to be an in and output paramter. Otherwise you would pass an copy of lista to function insHead and never get back its content.
void insHead( ListaLibri *lista )
// ^ input and outout paramter
{
if ( lista == NULL )
return;
Cella *head = lista->pFirst; // remember head of list
lista->pFirst = malloc(sizeof(Cella)); // allocate new node right to target
lista->pFirst->pNext = head; // successor of new node is head of list
if ( lista->pLast == NULL ) // if list was empty new node is tail of list
lista->pLast = lista->pFirst;
Libro libro;
printf("Inserisci titolo libro: ");
scanf("%s", libro.titolo);
printf("Inserisci autore libro: ");
scanf("%s", libro.autore);
printf("Inserisci il numero di copie presenti in libreria: ");
scanf("%d",&libro.inLibreria);
lista->pFirst->libro = libro;
printList( lista );
}
Don't delete nodes infunction print.
void printList(ListaLibri *lista)
{
if ( lista == NULL )
return;
Pcella temp = lista->pFirst;
while (temp != NULL)
{
printf("%s\n", temp->libro.autore);
temp = temp->pNext;
}
}
Write a function which deletes the list.
void deleteList(ListaLibri *lista)
{
if ( lista == NULL )
return;
Pcella temp = lista->pFirst;
while (temp != NULL) // terminate if tail of list is reached
{
Pcella next = temp->pNext; // rmember successor of node
free( temp ); // delete node
temp = next; // go to next node
}
lista->pFirst = NULL;
lista->pLast = NULL;
}
You are not assigning the pFirst value, so it is having garbage data, which is not equal to NULL.
Modify your code like this;
void insHead(ListaLibri lista)
{
// Your code goes here
lista.pFirst = NULL;
if(lista.pFirst == NULL)
{
// Your code goes here
}
printList(&lista); //Pass it as a reference, because printList() input parameter is a pointer type.
}
Hope this helps.
You declare lista in main, but you don't initialize any fields. My guess is that lista.pFirst is non-NULL garbage and you if is then skipped.
any idea why does my program crash after showing the right result? (i.e. i insert 6 2 4 3 he returns 2 3 4 6 but the console crashes right after!)
The main idea is to sort a linked list after the user giving the integers. I tried to solve it like if it was a bubble sort but for some reason it's not 100% operational. sorry for the portuguese comments!
#define ITEM_TYPE int
typedef struct lnode* List;
typedef struct lnode{
ITEM_TYPE info;
List next;
}List_node;
void ordenalista(List lista){
int contador = 0, i;
/* lista é uma lista recebida */
List head = lista; /* termos sempre disponível o início da lista*/
List actual = NULL; /*lista vazia, ou nó */
List temp = NULL;
if(head == NULL || head->next == NULL){ /* caso de lista vazia ou so com 1 elemento*/
printf("A lista esta vazia ou tem apenas um elemento");
return 0;
}
while(head != NULL){ /* contar quantos elementos tem a lista*/
contador++;
head = head->next;
printf("%d \n", contador);
}
for(i=0; i<contador; i++){ /* percorrer todos os elementos da lista*/
while(head->next != NULL){ /* enquanto não chegarmos ao final da lista*/
if(head->info > head->next->info){ /* se o valor do atual for maior que o valor do seguinte*/
temp = head->next;
head->next = head->next->next; /* não precisamos de usar actual->data, apenas precisamos de mudar os ponteiros*/
temp->next = head;
}
}
}
}
void ex213(){
int numero;
List lista;
lista = create_list();
while((scanf("%d",&numero)) == 1){ /* lê da esquerda para a direita. SCANF DÁ 1 SE INSERIR INTEIRO, 0 CASO CONTRÁRIO */
insertwithoutorder(lista, numero);
}
ordenalista(lista);
printlist(lista);
}
void insertwithoutorder(List lista, ITEM_TYPE it){
List no;
List ant, inutil;
no = (List)malloc(sizeof(List_node));
if (no != NULL) {
no->info = it;
searchwithoutorder(lista, it, &ant, &inutil);
/*while(ant->next != NULL){
ant = ant->next;
}*/
no->next = NULL;
ant->next = no;
}
}
void searchwithoutorder(List lista, ITEM_TYPE chave, List *ant, List*actual){
*ant = lista; *actual = lista->next;
while ((*actual) != NULL){
*ant = *actual;
*actual = (*actual)->next;
}
if ((*actual) != NULL && (*actual)->info != chave)
*actual = NULL; /* Se elemento não encontrado*/
}
void printlist(List lista){
List l = lista->next; /* Salta o header */
while (l){
printf("%d ", l->info);
l=l->next;
}
}
int main(){
ex213();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define ITEM_TYPE int
typedef struct lnode* List;
typedef struct lnode{
ITEM_TYPE info;
List next;
} List_node;
List create_list(void){
//top node unused
return calloc(1, sizeof(List_node));//note : might NULL != 0
}
List lastNode(List lista){
while (lista->next != NULL){
lista = lista->next;
}
return lista;
}
void insertwithoutorder(List lista, ITEM_TYPE it){
List no, ant;
no = create_list();
if (no != NULL) {
no->info = it;
no->next = NULL;
ant = lastNode(lista);
ant->next = no;
} else {
printf("failed to create a new node.\n");
}
}
void ordenalista(List lista){
List head = lista;
List actual, neighbor, sentinel = NULL;
if(head->next == NULL){
printf("A lista esta vazia\n");
return ;
}
while(head->next != sentinel){
actual = head->next;
neighbor= actual->next;
while(neighbor != sentinel){
if(actual->info > neighbor->info){
ITEM_TYPE temp = actual->info;
actual->info = neighbor->info;
neighbor->info = temp;
}
actual = neighbor;
neighbor= neighbor->next;
}
sentinel = actual;
}
}
void printlist(List lista){
List l = lista->next;
while (l){
printf("%d ", l->info);
l=l->next;
}
puts("");
}
void ex213(void){
int numero;
List lista = create_list();
while((scanf("%d", &numero)) == 1){
insertwithoutorder(lista, numero);
}
//printlist(lista);
ordenalista(lista);
printlist(lista);
//deallocate ?
}
int main(void){
ex213();
return 0;
}
The crash must be occurring in the function (now) named printlist(), as your program does nothing else after that function returns.
I don't see anything inherently wrong with printlist(), but it does depend on the list being in a valid state. In particular, my best guess at why the program fails where it does would be that the next pointer of the last list element contains a junk value instead of the expected NULL. You could verify that by running the program in a debugger.
How, then, might the list be corrupted?
Well, your insertion function looks ok. The searchwithoutorder() function on which it relies doesn't actually do what its name says, but it does do what insertwithoutorder() needs it to do.
That leaves the sort function, ordenalista(), and here I'm a bit flumoxed. I don't see how the version you posted could do any sorting at all. You have a while loop like so: while(head != NULL){...}, whithout any break or goto inside, so when control passes beyond this loop it must be that head == NULL. Then, without modifying the value of head, you go into a loop nest like this:
for(i=0; i<contador; i++) { /* percorrer todos os elementos da lista*/
while(head->next != NULL) { /* enquanto não chegarmos ao final da lista*/
...
}
}
But head is NULL at that point, so dereferecing it produces undefined behavior. If that behavior were not itself a crash, then correctly guessing and dereferencing the pointer you meant is an extremely unlikely alternative. Moreover, you do not modify head in the body of the loop, so it remains NULL. There are other problems with this loop, too.
As if all that weren't enough, there is also no good way for your sort function to change which element is at the head of the list -- at least none that would be effective for the caller.
So basically, I don't believe you have accurately described the problem. It must be either that the failure behavior you observed is different from what you described, or that the code you presented does not correspond to the program whose misbehavior you described.
When asking the user for data, it is useful to let the user know what you are asking for and how to handle/terminate any requests for input. A blinking cursor on a blank line tells the user nothing. (even when it is testing for you, it can help prevent an inadvertent keystroke of the wrong type). For example your ex213 function leaves a blinking cursor on a blank line leaving the user wondering "Is the program hung?" "Did it encounter a race condition?" etc.. When asking the user for linked-list data, a simple additional line or two of guidance can really help. Example:
void ex213 (void)
{
int numero;
List lista = create_list ();
printf ("\nEnter a number to add to the list [CTRL+D] when done:\n\n");
while (printf (" data: ") && (scanf ("%d", &numero)) == 1) {
insertwithoutorder (lista, numero);
}
ordenalista (lista);
printf ("\n\nThe ordered linked-list is:\n\n");
printlist (lista);
printf ("\n");
//deallocate ?
}
Output
$ ./bin/ll_single_sort
Enter a number to add to the list [CTRL+D] when done:
data: 2
data: 8
data: 20
data: 6
data: 9
data: 1
data:
The ordered linked-list is:
1 2 6 8 9 20
Adding that to the answer provided by BLUEPIXY provides the results you were looking for.
Hello guys i got a problem while running this code:
trying to run the printf in the comment i got a segfault, also without that i dont see my listed printed ad the function Stampa should do.
Probably i am missing something with pointers
#include <stdio.h>
#include <stdlib.h>
struct nodo { // double linked list
int info;
struct nodo *prec;
struct nodo *succ;
};
typedef struct nodo nodo;
struct nodo *Crealista(void);
void Stampa (struct nodo *nodo);
int main(int argc, const char * argv[]) {
struct nodo *p;
p = Crealista();
// printf("%d",p->succ->info);
Stampa(p);
return 0;
}
// this funct should print the whole list
void Stampa (struct nodo *p) {
while (p->succ != NULL ) {
printf("Value : %d \n", p->info);
p = p->succ;
}
}
// this funct should create list with n members and return a pointer to the first element
struct nodo *Crealista(void) {
struct nodo *p, *primo, *back;
int i, n;
p = NULL;
primo = NULL;
back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("inserisci %d numeri interi positivi: ", n);
for (i=0; i<n; i++) {
p = malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
back = p;
}
primo = p;
while (primo->prec != NULL) { primo = primo->prec;}
return(primo);
}
Stampa()
Let's look at what we want to do when we print the entire list:
If the current element is valid, then we want to print it.
Then, we want to iterate to the next element, and continue this loop.
That's not what your code does. Your code looks to see if the current element has a successor, and if it does, we print the current element's value.
That function should actually be:
void Stampa (struct nodo *p) {
while (p != NULL ) {
printf("Value: %d\n", p->info);
p = p->succ;
}
}
Crealista()
If you tell Crealista() to create a list of 0 elements, your final while loop will exhibit undefined behavior.
If you tell Crealista() to create a list of less than 2 elements, your commented printf() in main() will cause undefined behavior (if it was uncommented).
Doubly Linked Lists
You never update the value of nodo->succ. You only update the value of nodo->prev. Here's one example of how to do that:
if (p->prec)
p->prec->succ = p;
Putting all of this together
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct nodo {
int info;
struct nodo *prec;
struct nodo *succ;
};
typedef struct nodo nodo;
struct nodo *Crealista(void);
void Stampa (struct nodo *nodo);
int main(int argc, const char * argv[]) {
struct nodo *p;
p = Crealista();
Stampa(p);
}
// Print the list
void Stampa (struct nodo *p) {
while (p != NULL ) {
printf("Value: %d \n", p->info);
p = p->succ;
}
}
// Create a list of n elements
struct nodo *Crealista(void) {
int i, n;
struct nodo *p = NULL;
struct nodo *primo = NULL;
struct nodo *back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
assert(n != 0);
printf("inserisci %d numeri interi positivi: ", n);
for (i=0; i<n; i++) {
p = malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
if (p->prec)
p->prec->succ = p;
back = p;
}
primo = p;
while (primo != NULL && primo->prec != NULL)
primo = primo->prec;
return primo;
}
Which when run...
Numero di elementi: 5
inserisci 5 numeri interi positivi: 1 2 3 4 5
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
The printf() call you have commented out will always exhibit undefined behavior when p->succ is NULL, as it will be when p points to the last (or only) element of the list. In that case, although the behavior is formally "undefined", it is quite likely to manifest as a segmentation fault.
In stampa add check
while(p!=NULL)
{
printf("Value %d",p->info);
p=p->succ;
}
You are probably accessing it when it is not allocated. Check it this way there is no problem if it reaches a null value also. And initial null value will not cause problem also(if used).
I have modified your code
// this funct should create list with n members and return a pointer to the first element
struct nodo *Crealista(void) {
struct nodo *p, *primo, *back;
int i, n;
p = NULL;
primo = NULL;
back = NULL;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("inserisci %d numeri interi positivi: ", n);
p = (struct nodo *)malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->succ = NULL;
back = p;
for (i=1; i<n; i++) {
p = (struct nodo *)malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->prec = back;
p->prec->succ=p;
p->succ = NULL;
back = p;
}
primo = p;
while (primo->prec != NULL) { primo = primo->prec;}
return(primo);
}
You are not setting the succ pointer of previous node correctly. That is what causing you the problem. Check now.
it may be a nooby question, but can you explain me why running this i get printed the last member of the list instead of the first? am i missing something?
struct nodo {
int info;
struct nodo *prec;
struct nodo *succ;
} ;
typedef struct nodo nodo;
nodo *leggi_lista(void);
int main (void) {
struct nodo *q;
q= NULL;
q=leggi_lista();
printf("%d\n\n", q->info); //should print first member of the list
return 0;
}
nodo *leggi_lista(void) { //creating list
nodo *p, *primo=NULL;
int i, n;
printf("Numero di elementi: ");
scanf("%d", &n);
printf("Inserisci %d numeri: ", n);
for (i=0; i<n; i++) {
p = malloc(sizeof(struct nodo));
scanf("%d", &p->info);
p->succ = primo;
primo = p;
}
return (primo) ;}
aaand i dunno what else i can add the post helper is bullying me :(
You are returning primo from the function which holds the value in p and this is got by the last malloc() and obviously you see the last value being printed out.
You need to fix your function to create the list. You need to keep your list's head intact and return the head from the function and print from head to end of list.