why taking input with loop is giving seg fault whereas the commented part wors fine which means function is correct.please help!
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
node* head =NULL;
void push_front(int x){
node* temp = new node();
temp->data= x;
temp->next= head;
head=temp;
}
void push_back(int x){
node* temp =new node();
node* curr;
if(head==NULL){
temp->data=x;
head=temp;
curr=temp;
temp->next=NULL;
}
else{
temp->data=x;
curr->next=temp;
curr=temp;
temp->next==NULL;
}
}
void printit(node* node){
while(node!=NULL){
cout<<node->data<<" ";
node=node->next;
}
}
int main() {
int n;
cin>>n;
//giving segmentation fault
for(int i=0;i<n;i++){
int ip;
cin>>ip;
push_back(ip);
}
//push_back(1);
//push_back(2);
//push_back(3);
//push_back(4); gives output as 1 2 3 4 as required
printit(head);
return 0;
}
temp->next==NULL;
You are using ’==' here… In your push_back()
function’s else
's block.
But your code doesn’t seems to be working for just the commented part too.
While Pushing back, you have to iterate through each node to get to end and then insert your node there.
Hello @madhav76, welcome to Codechef Community.
I found the bug
.
Here you go.
Replace the cin>>
with scanf
This worked in OnlineGDB.
#include <bits/stdc++.h>
// #include <iostream>
using namespace std;
struct node
{
int data;
node* next;
};
node* head =NULL;
void push_front(int x){
node* temp = new node();
temp->data= x;
temp->next= head;
head=temp;
}
void push_back(int x){
node* temp =new node();
node* curr;
if(head==NULL){
temp->data=x;
head=temp;
curr=temp;
temp->next=NULL;
}
else{
temp->data=x;
curr->next=temp;
curr=temp;
temp->next==NULL;
}
}
void printit(node* node){
while(node!=NULL){
cout<<node->data<<" ";
node=node->next;
}
}
int main() {
int n;
scanf("%d",&n);
// giving segmentation fault
for(int i=0;i<n;i++){
int ip;
scanf("%d",&ip);
push_back(ip);
}
// push_back(1);
// push_back(2);
// push_back(3);
// push_back(4);
// gives output as 1 2 3 4 as required
printit(head);
return 0;
}
Happy Coding 
But frankly speaking, I don’t know why the previous one resulted in Segmentation Fault, while the other one worked fine.
i think you should add a name a the vector while doing the push_back() function