I am coding on inserting a node at the end in a singly LinkedList. Program is executing without any errors but running an infinite loop after entering the very first number. I can't find the logical error I have committed in the code. Any help would be appreciable :).
Here is the code and what I've tried:
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
node* head = NULL; // empty list
node* temp;
void insert(int x){
temp = (node*)malloc(sizeof(node));
temp -> data = x;
temp -> next = NULL;
if (head == NULL) head = temp;
node* temp1 = head;
// traversing the list
while(temp1 -> next != NULL){
temp1 = temp1 -> next;
}
temp1 -> next = temp;
}
void print(){
node* iterator = head;
while(iterator != NULL){
cout << iterator -> data;
iterator = iterator -> next;
}
}
int main(){
int n, x;
cout << "how many numbers\n";
cin >> n;
for(int i = 0; i < n; i++){
cout << "enter the value";
cin >> x;
insert(x);
print();
}
return 0;
}
I expect the output to be a linked list but the o/p is an infinite number of first entered number/data ('x' in this case)
Well the logic of the insert
function is clearly wrong
Lets step though it.
First you allocate the node and assign it to temp
. Since this is C++ you should use new and you should use a constructor, but we'll let that pass.
Then since head
equals NULL you set head
to the temp
.
Then you set temp1
to head
, which because of the previous step means temp1
equals temp
.
Then you loop to the last node pointed to by temp1
. In this case you're already at the last node so the loop isn't entered.
Then you set temp1->next
to temp
, but remember that temp1
equals temp
, (see two steps previous), so now you've created a circular list. This explains your infinite loop.
I'm guessing that you meant to write this
if (head == NULL) { head = temp; return; }
or maybe this
if (head == NULL)
{
head = temp;
}
else
{
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.