Reputation: 2656
So this is a very simple program to create and display a linked list. Here I'm getting caught in the display loop, and I'm seeing infinite '2->2->2->...' on screen.
After debugging, I can see that my program ALWAYS goes into the if
statement of insertNode()
whereas it should only go there ONCE i.e. when the linked list is initialized.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
struct node * head = NULL;
struct node * curr = NULL;
void insertNode(struct node * temp2) {
if (head == NULL) {
head = temp2;
head->next = NULL;
}
else {
temp2->next = head;
head = temp2;
}
}
void display() {
curr = head;
while (curr->next != NULL)
{
printf("%d->",curr->data);
curr = curr->next;
}
}
void main() {
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->data = 5;
insertNode(temp);
temp->data = 6;
insertNode(temp);
temp->data = 1;
insertNode(temp);
temp->data = 2;
insertNode(temp);
display();
}
Upvotes: 0
Views: 310
Reputation: 304
In you main you have one pointer to the temp and you continue inserting the same node and it ends up pointing to itself. You now have a circular list that's why you have an infinite loop.
Upvotes: 1
Reputation: 952
You are setting next of temp2
to head, and then head to temp2
. So in fact next node of temp2
is temp2
, that's why you have infinite loop.
Upvotes: 1
Reputation: 1282
You are getting an infinite loop because you only have one node. Doing temp->data = 5;
and then temp->data = 6;
does not create a new node. So when you add the same node into the list again, the next
pointer in the node points to itself. So your while loop in display never terminates, because the next
node is always the current node.
Upvotes: 0
Reputation: 53376
You should allocate and create new node for each data when inserting it in the linked list.
void main() {
struct node * temp = (struct node *) malloc (sizeof(struct node));
temp->data = 5;
insertNode(temp);
temp = malloc (sizeof(struct node));
temp->data = 6;
insertNode(temp);
temp = malloc (sizeof(struct node));
temp->data = 1;
insertNode(temp);
temp = malloc (sizeof(struct node));
temp->data = 2;
insertNode(temp);
display();
}
As you are using same node to add as multiple nodes, its making the circular list.
Your insertNode()
looks ok.
Upvotes: 2