Segmentation fault when creating two link lists - c++

The below C++ code raises a segmentation fault error. When only one linked list is created and displayed everything works file. But after introducing the second list causes error.
Goal here is to create and display two linked lists.
#include<iostream>
using namespace std;
struct node {
int value;
node* link;
};
void insert_into_list(node** head, int value) {
node* temp = new node;
temp->value = value;
temp->link = (*head);
(*head) = temp;
}
void display_link(node* he) {
cout << "Link List:\n";
node* head = he;
while (head != NULL) {
cout << head->value;
if (head->link != NULL)
cout << "->";
head = head->link;
}
cout << endl;
}
int main() {
node* head1;
node* sec;
insert_into_list(&head1, 9);
insert_into_list(&head1, 7);
insert_into_list(&head1, 6);
display_link(head1);
cout<<"LKL"<<endl;
insert_into_list(&sec, 8);
insert_into_list(&sec, 6);
insert_into_list(&sec, 7);
display_link(sec);
}

Your program has undefined behaviour because variables
node* head1;
node* sec;
were not initialized.
Use instead
node* head1 = 0;
node* sec = 0;

It is a mystery it worked for head1.
You should give your list a proper ending.
node* head1 = 0;
You would also help yourself if you provided your node with a constructor, like
node(int value, node* next);

Related

Linked List insertion isn't working in for/while loop

I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.
#include <iostream>
class Node {
public:
int data;
Node *next;
Node(int &num) {
this->data = num;
next = NULL;
}
};
class LinkedList {
Node *head = NULL;
public:
void insert(int num) {
Node *tmp;
if (head == NULL) {
head = new Node(num);
tmp = head;
} else {
tmp->next = new Node(num);
tmp = tmp->next;
}
}
void printList() {
Node *tmp = head;
while (tmp) {
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList() {
Node *curr = head, *prev = NULL, *nextNode;
while (curr) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main() {
LinkedList list1;
// This is not working
int num;
while (num != -1) {
std::cin >> num;
list1.insert(num);
}
// This is working
// list1.insert(1);
// list1.insert(2);
// list1.insert(3);
// list1.insert(4);
// list1.insert(5);
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}
I expect this after insertion
Edit:
although #Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?
for (int i = 1; i <= 10; i++)
{
list1.insert(i);
}
When inserting the nth item (1st excluded) tmp is a null pointer, i don't understand what you are doing there, you are assigning to next of some memory then you make that pointer point to another location, losing the pointer next you assigned before, you must keep track of the last item if you want optimal insertion. This way you are only assigning to some *tmp then going out of scope loses all your data... The best way is to just keep a pointer to the last inserted item, no need to use *tmp.
class LinkedList
{
Node *head = NULL;
Node *tail = NULL;
public:
void insert(int num)
{
if (head == NULL)
{
head = new Node(num);
tail = head;
}
else
{
tail->next = new Node(num);
tail = tail->next;
}
}
...
}
You need to loop until you reach the end of the list and then add the new node after that. Like this.
void insert(int num) {
Node *tmp = head;
if (head == NULL) {
head = new Node(num);
}
else {
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp->next = new Node(num);
}
}
first of all you need to define a node for each of the tail and head of the list as follows
Node *h;
Node *t;
you may also separate the Node from the LinkedList class so you can modify easily
class Node{
public:
int data;
Node *next;
Node(int data, Node* next);
~Node();
};
Node::Node(int data, Node* next)
{
this->data= data;
this->next= next;
}
Node::~Node(){}
}
after that you can try to add these functions to your LinkedList class
so it can deal with other special cases such empty list or full, etc..
void addToHead(int data){
Node *x = new Node(data,h);
h=x;
if(t==NULL){
t=x;
}
void addToTail(int data){
Node *x = new Node(data,NULL);
if(isEmpty()){
h=t=x;
}
else
{
t->next=x;
t=x;
}
}
now for the insert function try this after you implemented the Node class and the other functions,
void insert(int v){
if(h==nullptr){addToHead(v); return;}
if(h->data>=v) {addToHead(v);return;}
if(t->data<=v) {addToTail(v); return;}
// In this case there is at least two nodes
Node *k=h->next;
Node *p=h;
while(k != nullptr){
if(k->data >v){
Node *z =new Node(v,k);
p->next=z;
return;
}
p=k;
k=k->next;
}
}
the idea of making all of this is not lose the pointer when it goes through elements in the Linked List so you don't end up with a run time error.
I hope this can be useful to you.
There was an issue with your insert function.
Read about segmentation fault here https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/#:~:text=Core%20Dump%2FSegmentation%20fault%20is,is%20known%20as%20core%20dump.
for a quick workaround you can use this
using namespace std;
#include <iostream>
class Node
{
public:
int data;
Node *next;
Node(int num)
{
this->data = num;
next = NULL;
}
};
class LinkedList
{
Node *head = NULL;
public:
void insert(int num)
{
Node *tmp= new Node(num);
tmp->next=head;
head=tmp;
}
void printList()
{
Node *tmp = head;
while (tmp)
{
std::cout << tmp->data << " ";
tmp = tmp->next;
}
std::cout << std::endl;
}
void reverseList()
{
Node *curr = head, *prev = NULL, *nextNode;
while (curr)
{
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev;
}
};
int main()
{
LinkedList list1;
// This is not working
int num,i=0,n;
cout<<"Type the value of n";
cin>>n;
while (i<n)
{
cin >> num;
cout<<num<<" "<<&num<<endl;
list1.insert(num);
i++;
}
list1.printList();
list1.reverseList();
list1.printList();
return 0;
}

C++ Linked List Not Preserving New Nodes

I'm trying to transition from an almost entirely Java background to getting comfortable with C++. I'm practicing by trying to build a basic Linked List.
#include <iostream>
#include <string>
using namespace std;
struct node
{
string data;
node *next = NULL;
};
class linkedlist
{
public:
node *head;
public:
linkedlist()
{
head = NULL;
}
void addNode(string s)
{
node *newNode = new node;
newNode->data = s;
if(head == NULL)
head = newNode;
else
{
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
}
}
void printList()
{
node *temp = head;
while(temp != NULL)
{
cout << temp->data << '\n';
temp = temp->next;
}
}
};
The issue at hand is that once I add a new node using void addNode(string s), it does not appear when I attempt to print the list (starting from the head) with void printList().
For example:
int main(int argc, const char * argv[])
{
int n;
string str;
linkedlist list;
cout << "Please enter the number of strings you'd like to enter:\n";
cin >> n;
for(int i = 0;i < n;i++)
{
string temp;
cout << "Enter string #" << i + 1 << '\n';
cin >> temp;
list.addNode(temp);
}
cout << "This is your linked list: ";
list.printList();
return 0;
}
Using main() above, my results become:
This is your linked list:
(string 1)
I'm pretty certain I'm using pointers improperly here but I don't see why. I've done as much digging as I can on my own for some clarification on how I could be doing this wrong but I'm coming up blank.
Thanks for any clarification you folks can provide.
The problem is here:
node *temp = head->next;
while(temp != NULL)
temp = temp->next;
temp = newNode;
You're traversing the list, then setting temp to the value of the newNode. When temp goes out of scope, the value for newNode isn't stored anyplace.
What you want to do is set the next pointer of the last node to the value of newNode, i.e.
node *temp = head;
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
The code above traverses the list until it finds a node that doesn't have a next node, and sets its next node to the newNode, thus adding it to the list.

LinkedList only adds two elements in C++

I am trying to learn linkedlist in c++, I am facing a problem as linkedlist is only adding 2 elements.
code:
struct Node {
int data1;
Node* next;
};
void firstElement(Node *&head, int d)
{
Node* temp = new Node;
temp->data1 = d;
temp->next = NULL;
head = temp;
}
void insert(Node *&node, int data)
{
Node* temp = new Node;
temp->data1 = data;
temp->next = NULL;
while(node)
{
if(node->next == NULL)
{
node->next = temp;
return;
}
node = node->next;
}
}
void display(Node *&node)
{
while(node != NULL)
{
cout << node->data1 << endl;
node = node->next;
}
}
int main()
{
Node* head;
firstElement(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
insert(head, 5);
insert(head, 6);
insert(head, 7);
insert(head, 8);
insert(head, 9);
insert(head, 10);
display(head);
}
In the output, it only gives me value 9 and 10 i.e only the last 2 elements. Looks like it's just replacing the values. However, I am not getting it. For my temp node I am already initializing it to next i.e temp->next = NULL.
And in insert() function, i am using an if condition to only add next node if its NULL.
Any suggestions?
The problem comes from insert function. It takes a Node* & so as soon as you do
node = node->next;
in the loop, it will modify the variable used by caller as the node parameter list.
Remove & and your problem is solved :
void insert(Node* node, int data)

Linked list Behaviour

Can Someone please explain the difference in Behaviour ?
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
// only for the 1st Node
void initNode(Node *head,int n){
head->data = n;
head->next =NULL;
}
void insertFront(Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = head;
head = newNode;
}
void display(Node *head) {
Node *list = head;
while(list) {
cout << list->data << " ";
list = list->next;
}
cout << endl;
cout << endl;
}
int main()
{
Node *l1 = new Node;
initNode(l1,10);
display(l1);
insertFront(l1,5);
display(l1);
insertFront(l1,6);
display(l1);
insertFront(l1,7);
display(l1);
return 0;
}
Some how the nodes are not linking. The output is :
10
10
10
10
If The program is coded using pointer to a pointer as below then it works fine. what am is missing ?
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
// only for the 1st Node
void initNode(Node *head,int n){
head->data = n;
head->next =NULL;
}
void insertFront(Node **head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = *head;
*head = newNode;
}
void display(Node *head) {
Node *list = head;
while(list) {
cout << list->data << " ";
list = list->next;
}
cout << endl;
cout << endl;
}
int main()
{
Node *l1 = new Node;
initNode(l1,10);
display(l1);
insertFront(&l1,5);
display(l1);
insertFront(&l1,6);
display(l1);
insertFront(&l1,7);
display(l1);
return 0;
}
Output correct as expected :
10
5 10
6 5 10
7 6 5 10
In the first case, in function
void insertFront(Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = head;
head = newNode;
}
head is a copy of the pointer l1 used in the scope of main(). When head is modified, l1 is left unchanged. This is the reason why a pointer to l1 (&l1) is passed to the function in the second case void insertFront(Node **head, int n). Then *head is l1, not just a copy of l1.
First case is an example of passing argument by value, and the second case is passing an argument by reference What's the difference between passing by reference vs. passing by value?
For instance, the following function is basically useless :
void useless(int a){
a=42;
}
If int b=2;useless(b);cout<<b<<endl; is called it will print 2, not 42.
The following function is the right way to go :
void rightwaytogo(int*a){
*a=42;
}
Don't forget to write a function to delete the nodes of your linked list.

Linked list problem

I got some problem with the linked list I've written. I dunno if it's either my insert function that the problem, or if it's my traverse function that's not correct. I hope for some input. A side note, I'm initalising the list in main now since I don't know if my initNode function is correct.
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
Node *next;
};
void initNode(Node *head)
{
head = new Node;
head->next = NULL;
}
void insertNode(Node *head, int x)
{
Node *temp;
temp = new Node;
temp->data = x;
temp->next = head;
head = temp;
}
void traverse(Node *head)
{
Node *temp;
temp = head;
if(head == NULL)
{
cout << "End of list. " << endl;
}
else
{
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
}
int main()
{
Node *head;
head = NULL;
insertNode(head, 5);
insertNode(head, 5);
traverse(head);
return 0;
}
Your head isn't being returned to main from insertNode. Note that even though head is a pointer, the pointer itself is a value and any changes to the pointer value are not reflected in main. The simplest solution is to pass back the updated value of head:
Node *insertNode(Node *head, int x)
{
...
return head;
}
And update it in main:
head = insertNode(head, 5);
The other common way of doing this is to pass a pointer to a pointer and update it directly:
void insertNode(Node **head, int x)
{
Node *temp;
temp = new Node;
temp->data = x;
temp->next = *head;
*head = temp;
}
And call it like this:
insertNode(&head, 5);
The way you have you initNode function written will result in memory leaks. You've passed in a pointer, but you need to pass in a reference to a pointer. (Same issue that James and casablanca mentioned for insertNode.)