program crashes while running linked list program - c++

this is the code
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
Node *head;
`insert function takes a number as argument`
void insert(int a)
{
Node *temp = new Node();
temp -> data= a;
temp->next = head;
head = temp;
}
void print(void)
{
Node *temp1;
temp1 = head;
while(head != NULL)
{
cout<<temp1->data<<endl;
temp1 = temp1->next;
}
}
**main function**
int main()
{
head = NULL;
int a;
int b;
cout<<"how many elements do you want to insert";
cin>>b;
for (int i = 0;i < b; i++)
{
cout<<"enter a number"<<endl;
cin>>a;
insert(a);
print();
}
return 0;
}
when I enter the number to insert it shows program has stopped working. I am trying to insert numbers to linked list and print it ever time I add a number.I have checked for many other errors but it has none.

Looks like it might be due to an infinite loop like one of the comments says. Try updating the loop in the print function like this:
void print() {
Node *temp1;
temp1 = head;
// Here, I switched `head` with `temp1`
while (temp1 != nullptr) {
std::cout << temp1->data << std::endl;
temp1 = temp1->next;
}
}

Related

what is the problem in creat_list2 function?

I want to know what is the problem in creat_list2 function..
I have a problem in this code and as i knew it's in the creat_list2 cause the program run Successfully
when i stop this function it ask the user to enter a numbers that will be stored in the list 1 then print them but the problem as i saw is in the second fuction that creat the second list...,I have to submit my assignment tomorrow so I wish if any body can help me to solve this problem.
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
struct snode{
int y;
snode *next;
};
creat_list1(node *&head, node *&tail)
{
int num;
cout<<"enter number\n";
cin>>num;
while(num!=0)
{
node *np=new node;
np->x=num;
if(head==nullptr)
head=np;
else
tail->next=np;
tail=np;
tail->next=nullptr;
cout<<"enter number again\n";
cin>>num;
}
}
creat_list2(node *&head, snode *shead, snode *stail)
{
int sum=0;
while(head!=nullptr)
{
for(int i=0;i<head->x;i++)
sum+=i;
snode *np= new snode;
np->y=sum;
if(head==0)
shead=np;
else
stail->next=np;
stail=np;
stail->next=nullptr;
}
head=head->next;
}
void print_list1 (node *head)
{
while(head!=nullptr)
{
cout<<head->x<<"\t";
head=head->next;
}
}
void print_list2(snode *shead)
{
while(shead!=nullptr)
{
cout<<shead->y<<"\t";
shead=shead->next;
}
}
main()
{
node *head=nullptr, *tail=nullptr;
snode *shead=nullptr, *stail=nullptr;
creat_list1(head,tail);
creat_list2(head,shead,stail);`enter code here`
print_list1(head);
print_list2(shead);
}
There are couple of issues with yours code,
creat_list2(node *&head, snode *shead, snode *stail) if u updated
head like head=head->next; it will reflect at the main.
shead and stail are just a local pointer and any update to just a pointer like stail=np;will not have any changes at the `main
There seems to be typo if(head==0) shead=np; instead it should be
if(shead==0) shead=np; which is causing null pointer exception.
I tried to fix the error at creat_list2 but functionality is still ambiguous to me,
void creat_list2(const node *head, node *&shead, node *&stail) //updated in argument
{
int sum = 0;
while (head != nullptr)
{
//for (int i = 0; i < head->x; i++)
// sum += i;
node *np = new node;
np->x = sum;
if (shead == 0) //error : head instead shead
shead = np;
else
stail->next = np;
stail = np;
stail->next = nullptr;
head = head->next;
}
}

Creating and printing linked list from user input C++

#include <iostream>
using namespace std;
int main()
{
struct node
{
int data;
node * next;
};
node * head;
node * n;
node * temp;
node * q;
int number;
cout << "Enter numbers";
cin >> number;
n = new node;
n->data = number;
head = n;
temp = n;
while (cin >> number)
{
while (number != -500)
{
n = new node;
n->data = number;
temp->next = n;
temp = n;
}
}
while (head != NULL)
{
cout << head->data;
head = head->next;
}
}
I don't understand why this would not work. The program creates a new node then sets whatever the user entered equivalent to the variable data of that new node then it makes head and temp point to the new node. Then it gets the users second input and compares it to -500 and if it evaluates as true it creates a new node puts the data of the second input into the variable data then it links the first node and second node together then it makes temp point to the second node. If the condition of the 2nd while loop is false it goes to the third which is where it is suppose to print the list.
Who sets the last node's next to NULL?
At n = new node; n->next is not NULL but undefined, in Debug versions usually it is 0xcccccccc or something similar value to make it visible that it is not initialized. If you try to dereference it, you will get an access violation.
while (cin >> number) { // this loop is endless, because you can always read the user input data (unless some exception happen)
while (number != -500)
{
n = new node; // you already have data allocated. no need to allocate it once more
n->data = number;
temp->next = n;
temp = n;
// as was already mentioned: set n->next to NULL
} }
if you want to break after you checked that the number is not -500, then you can do the following instead:
while (cin >> number) {
if (number != -500) { ...; // do your stuff
break;
}
}
And, by the way, you have a memory leak. If you use flat C pointers then consider delete operator to clear your memory. For that purpose, you need to know where your list starts(basically, head) and iterate through a whole list invoking delete node.
Please, also consider, that it is a bad code style to write something like:
while (cin >> number)
You can also try this-
This code makes a linked list on user input and printlinkedlist (function) print the linked list created.
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
node* next;
};
void printlinkedlist(node* node)
{
int c=0; //taken just for good looking output
while(node!=NULL)
{
if(c>0)
{
cout<<"->"<<node->data;
node = node->next;
}
else
{
cout<<node->data;
node = node->next;
c++;
}
}
}
int main() {
int n;
cout<<"Enter no. of nodes=";
cin>>n; //User enters number of nodes he want.
int num,c=0; //initialized c for setting head with second node..
node* head = new node; //initialized head node
node * temp = new node; //initialized temp node
cin>>num;
head->data=num;
for(int i=2;i<=n;i++)
{
if(c==0)
{
cin>>num;
temp->data=num;
head->next=temp; //head point to second node i.e. temp
c++;
}
else
{
cin>>num;
node * temp1 = new node; //initialize other temp node for every value
temp1->data=num;
temp->next=temp1; //point to temp1 to temp
temp=temp1; //set temp as temp1
}
}
printlinkedlist(head);
}
#include<iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
// a function to create linked list passing pointer to pinter
void create_list(node**head)
{
int num;//num is the data
cin>>num ;
node*new_node=new node();//
new_node->data=num;
new_node->next=NULL;
node*temp;
if(*head==NULL)
{
*head=temp=new_node;
}
else{
temp->next=new_node;
temp=new_node;
}
}
void print_list(node* head)
{
if(head == NULL)
{
cout<<"empty list"<<endl;
}
node *ptr = NULL;
ptr=head;
cout<<"data in the list: "<<endl;
while(ptr!=0)
{
cout<<ptr->data<<endl;
ptr=ptr->next;
}
}
int main()
{
int n,i; //
cout<<"enter the number of nodes:"<<endl;
cin>>n;
cout<<"enter data as num:"<<endl;
node* head=NULL;
for(i=0;i<n;i++)
{
create_list(&head);//passing the address of head
}
print_list(head);
return 0;
}

After exiting from function, nodes aren't saved

My program should create a linked list and show it. My problem is when the addelemnt_end function ends, it doesn't update head and last.
I tried with debug and when my function is done, the info and next part from head and last are "unable to read memory".
struct node{
int info;
node *next;
};
node *head, *last;
void addelement_end(node *head, node *last, int element)
{if (head == NULL)
{ node *temp = new node;
temp->info = element;
temp->next = NULL;
last = temp;
head = temp;
}
else {node*temp = new node;
last->next = temp;
temp->info = element;
temp->next = NULL;
last = temp;
}
}
void show(node* head, node *last)
{
if (head==NULL)
cout << "Empty list";
else
while (head != NULL)
{
cout << head->info << " ";
head = head->next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int x, n, i;
cout << "how many numbers";
cin >> n;
head = last = NULL;
for (i =1; i <= n; i++)
{
cin >> x;
addelement_end(head, last, x);
}
show(head, last);
return 0;
}
It's a very common error. Here is a similar illustration of the problem:
int change_a(int a) {
a = 42;
}
int main() {
int a = 10;
change_a(a);
printf("%d\n", a);
return 0;
}
This will print 10 because in the function change_a you are only modifying a copy of the value contained in the variable a.
The correct solution is passing a pointer (or using a reference since you are using C++).
int change_a(int *a) {
*a = 42;
}
int main() {
int a = 10;
change_a(&a);
printf("%d\n", a);
return 0;
}
But maybe you're going to tell me: "I'm already using a pointer!". Yes, but a pointer is just a variable. If you want to change where the pointer points, you need to pass a pointer to that pointer.
So, try this:
void addelement_end(node **head, node **last, int element)
{
if (*head == NULL)
{ node *temp = new node;
temp->info = element;
temp->next = NULL;
*last = temp;
*head = temp;
}
else {
node *temp = new node;
(*last)->next = temp;
temp->info = element;
temp->next = NULL;
*last = temp;
}
}

C++ doubly linked list

I got a problem with my doubly linked list. How can i make the input unique ( i don`t want it to be repeated )
for example i can input 1 and then again 1 i will have a list of 1 and 1. I need to forbid this somehow :) so the list can contain only not repeating numbers.
#include <cstdlib>
#include <iostream>
using namespace std;
struct node
{
int data;
node* next;
node* prev;
};
class Node
{
public:
Node();
~Node();
void setKopa();
void printForward();
private:
node* head;
node* tail;
node* n;
};
Node::Node()
{
setKopa();
}
Node::~Node()
{
delete n;
}
void Node::setKopa()
{
int lenght;
do
{
cout << "Input list lenght (how many elements): ";
cin >> lenght;
if(lenght<2)
cout << "Error list has to have atleast 2 elements!" <<endl;
}
while(lenght<2);
int fill;
cout << "Input "<< lenght <<" elements: "<<endl;
for (int i=0; i<lenght; i++)
{
cin>>fill;
n = new node;
n->data = fill;
if (i==0)
{
n->prev = NULL;
head = n;
tail = n;
}
else if (i+1==lenght)
{
n->prev = tail;
tail->next = n;
tail = n;
tail->next = NULL;
}
else
{
n->prev = tail;
tail->next = n;
tail = n;
}
}
}
void Node::printForward()
{
node* temp = head;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp-> next;
}
cout << endl;
}
int main()
{
Node a;
a.printForward();
system("pause");
return 0;
}
When you read input, go through the list to see if the input is already there.
With that (simple) answer out of the way, I would like to address some other things regarding your code. The first is that you have a memory leak in that you never delete the list. The second is that you don't need the class member variable n, it might as well be a local variable inside the setKopa loop.
Your way of adding new nodes is also, well, weird. It should, in my opinion, be more general instead of using the loop counter to check what to do. What I suggest is that you make a member function to add new nodes, taking the integer data as argument. This way you can call this function to add nodes anywhere, and not just in the setKopa function. In fact, I think the list should not handle that input at all, instead it should be a free-standing function called from main and which calls the addNode function.
Also the node structure doesn't need to be in the global namespace, it could be a private structure in the Node class. And speaking of the Node class, shouldn't it really be called List instead?
So if I may suggest, you might want to do something like this:
#include <iostream>
class List
{
public:
List()
: head(nullptr), tail(nullptr)
{}
~List();
void addNode(const int data);
void printAll() const;
private:
struct node
{
node()
: next(nullptr), prev(nullptr)
{}
node* next;
node* prev;
int data;
};
node* head;
node* tail;
};
List::~List()
{
for (node* next, *cur = head; cur; cur = next)
{
next = cur->next;
delete cur;
}
}
void List::addNode(const int data)
{
node* n = new node;
n->data = data;
if (tail == nullptr)
{
// First node in list
head = tail = n;
}
else
{
n->prev = tail;
tail->next = n;
tail = n;
}
}
void List::printAll() const
{
std::cout << "{ ";
for (node* cur = head; cur != nullptr; cur = cur->next)
std::cout << cur->data << ' ';
std::cout << "}\n";
}
int main()
{
List list;
for (int i = 0; i < 10; ++i)
list.addNode(i);
list.printAll();
}
The above code should print
{ 0 1 2 3 4 5 6 7 8 9 }
Replace the node-adding loop with your own.

Weird segmentation fault that disappears on using cout

I'm trying out a basic program that will randomly initialize a linked list and print the value at a user-specified index (getnth). However, I'm running into a weird segmentation fault that appears when I comment out a specific cout line, and disappears when I uncomment it.
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int x;
node *next;
};
void ins(struct node*& headRef, int n)
{
node *newNode = new node;
if (!newNode)
return;
newNode->x = n;
if (!headRef)
newNode->next = NULL;
else
newNode->next = headRef;
headRef = newNode;
cout<<"\n"<<n<<" inserted at "<<headRef<<"\n\n";
}
void disp(struct node* head)
{
node *temp = head;
if (!temp)
{
cout<<"\n\nLL empty\n";
return;
}
while (temp)
{
cout<<temp->x<<" ";
temp = temp->next;
}
cout<<"\n\n";
}
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
}
cout<<"\nIndex too high\n";
}
int main()
{
node *head;
int i;
srand(time(NULL));
for (i=0; i<10; i++)
{
ins(head, rand()%10+1);
cout<<"Main head is "<<head<<"\n"; // segfault appears if this line is commented out, disappears if it's not
}
cout<<"\nInitial LL\n\n";
disp(head);
cout<<"\nEnter index ";
cin>>i;
getnth(head, i);
return 0;
}
In main initialize
node *head=NULL;
and your getnth is wrong , fix it.
May be something like this :-
void getnth(struct node* head, int n)
{
int i=0;
node *temp = head;
while (temp)
{
if (++i == n)
{
cout<<"\n"<<temp->x<<"\n\n";
return;
}
temp=temp->next;
}
cout<<"\nIndex too high\n";
}
By default, the pointer "head" in "main( )" is initialized with garbage, because it's automatic variable allocated on program stack.
So, when you pass the pointer "head" to the function "disp( )", this pointer is dereferenced and it causes segmentation fault.
You have to initialize the pointer "head" with 0 explicitly, and this will fix the problem.