Reputation: 167
I'm practicing with linked lists in c, I want to make a program that reads entries from keyboard and lists the contents of the linked list after adding each node, but the output is always the first node, i can't figure out why, could someone please point out the flaw in this code:
#include <stdio.h>
#include <stdlib.h>
typedef int ID;
typedef struct node {
ID id;
struct node * next;
} node_t;
int main(){
node_t * head;
node_t * conductor;
head = NULL;
ID id;
int i=0;
while(i<10){
printf("Introduce an id:\n");
scanf("%d", &id);
if(head == NULL){
head = malloc(sizeof(node_t));
head->id = id;
head->next = NULL;
}
else{
conductor = head;
while(conductor != NULL)
conductor = conductor->next;
conductor = malloc(sizeof(node_t));
conductor->id = id;
conductor->next = NULL;
}
conductor = head;
printf("the list contains these elements:\n");
while(conductor != NULL){
printf("%d\n", conductor->id);
conductor = conductor->next;
}
++i;
}
}
Upvotes: 0
Views: 128
Reputation: 1980
You are running off the end of the list before inserting. You should go till conductor->next becomes NULL , insert new node and set conductor->next to point to the new node.
Some other pointers:
addNode
, removeNode
, printList
etc, Upvotes: 2
Reputation: 53699
You need something like the following
conductor = head;
// Find the last node in the list
while(conductor->next != NULL)
conductor = conductor->next;
// Setup the new node
node_t* newNode = malloc(sizeof(node_t));
newNode->id = id;
newNode->next = NULL;
// Have the last node's next pointer point to the new node
constructor->next = newNode;
The key is that you move constructor to the last node in the list, the new node will be wired into the list following the last node.
Typically with a linked list you should keep track of the current head and tail, this will improve performance when adding new nodes, you will note need to traverse the existing list everytime.
Upvotes: 1
Reputation: 1920
He problem is in your while loop at
while (conductor != NULL)
To add a new node, you need to set conductor->next, after finding the last conductor. Something like this could work:
While (conductor->next != NULL)
Upvotes: 2