I hope this question wasn't asked before. I tried searching for an answer but couldn't find any. I'm trying to learn pointers and linked lists in C++. this is my code so far
#include <iostream>
using namespace std;
struct node{
int value;
node* next;
};
node createNode(int value){
node temp;
temp.value = value;
temp. next = NULL;
return temp;
}
void add( node*& head, int value){
node temp = createNode(value);
// the problem is in this if statement
if (head->next == NULL){
head->next = &temp;
}
}
int main() {
node* head;
add(head,4);
cout<<head->next->value;
return 0;
}
if I try to grab the address of temp into the head, in my main function, the cout will print this value "1634545454" and If I move the code line "head->next = &temp;" outside of the if statement, it'll print the correct result which is 4. I don't understand why is that happening! what is that value? is the condition inside the if statement doing anything to the address, or the value of head->next?
You're declaring temp as a node (note the lack of *), i.e. a local variable. So it's automatically being freed at the end of the function.
Roughly speaking, you need to decide how you want to manage your memory. If you're going to do it all yourself, you need to use node* everywhere and remember to free your data structures when they go out of scope. But the more modern, safer approach would be to use unique_ptr<node>, which correctly captures that your node owns its next pointer. In this way, the data will be freed automatically when the time comes, but not before.
as #Silvio Mayolo mentioned you have two choices of using self managing memory or smart pointers , but as your base code was written in the self managing way ive fixed some of the pointers in your code.
the node pointer named head was not memory allocated and the temp variable most be a pointer so that the lifecycle dosent exceeds ,and if your using c++11 and above using nullptr would be better.
#include <iostream>
using namespace std;
struct node{
int value;
node* next=nullptr;
};
node* createNode(int value){
node* temp=new node;
temp->value = value;
temp->next = nullptr;
return temp;
}
void add( node* head, int value){
node* temp = createNode(value);
if (head->next == nullptr){
head->next = temp;
}
}
int main() {
node* head=new node;
add(head,4);
cout<<head->next->value;
return 0;
}
#include<iostream>
using namespace std;
struct node{
int value;
node* next=NULL; //node* next;
};
node* createNode(int value){ //node createNode(int value){
node* temp=new node; //node temp;
temp->value = value;
temp->next = NULL;
return temp;
}
void add( node* head, int value){ //void add( node*& head, int value){
node* temp = createNode(value); //node temp = createNode(value);
if (head->next == NULL){
head->next = temp; //head->next = &temp;
}
}
int main() {
node* head=new node; //node* head;
add(head,4);
cout<<head->next->value;
return 0;
}
Related
I have given insert and a print function to insert data in a linked list and then print it.
But somehow it does not give any output and keeps running for a infinite time.
What is wrong?
Here is the code I have written. This is a simple program to create a linked list using loops and functions.
#include<iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead=head;
if (temphead == NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead == NULL){
head==temp;
}
}
else if (temphead != NULL)
{
node* temp = new node();
temp->data=data;
temp->next=NULL;
while (temphead != NULL)
{
temphead->next= temp;
temphead=temphead->next;
}
}
}
void print(){
struct node* tempptr = head;
while (tempptr->next != NULL)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=NULL;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
There were few bugs in your code and also typos. Please read the comments marked with // CHANGE HERE for the description of the changes I did:
#include <iostream>
using namespace std;
struct node{
int data;
struct node* next;
};
struct node* head;
void insert(int data){
struct node* temphead = head;
if (temphead == nullptr)
{
node* temp = new node();
temp->data = data;
temp->next = nullptr;
// CHANGE HERE: removed unnecessary while loop
// Directly assign temp to head
head = temp;
}
else
{
node* temp = new node();
temp->data=data;
temp->next=nullptr;
// CHANGE HERE: check for temphead->next instead of temphead
while (temphead->next != nullptr)
{
// CHANGE HERE: remove unnecessary line: temphead->next= temp;
temphead=temphead->next;
}
// CHANGE HERE: assign temp to temphead->next (i.e. to last node)
temphead->next = temp;
}
}
void print(){
struct node* tempptr = head;
// CHANGE HERE: check for tempptr instead of tempptr->next
while (tempptr != nullptr)
{
cout<<tempptr->data<<"_";
tempptr=tempptr->next;
}
}
int main(){
head=nullptr;
insert(2);
insert(4);
insert(8);
insert(6);
//list - 2_4_8_6
print();
return 0;
}
NOTE: Your code uses new for dynamic memory allocation but doesn't use delete to de-allocate the memory when not required. If you want to avoid using new/delete, you can explore about smart pointers.
#include<iostream>
#define print(x) std::cout<<x<<std::endl;
class Node
{
public:
int data;
Node* next;
};
class LinkedList
{
private:
Node** head_ref;
public:
LinkedList() :head_ref(NULL) {};
void insertFront(int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
if(this->head_ref == NULL)
this->head_ref = &new_node;
else
{
new_node->next = *(this->head_ref);
this->head_ref = &new_node;
}
}
void PrintLinkedList()
{
Node* temp = (*(this->head_ref));
while (temp->next != NULL)
{
print(temp->data);
}
print("\n");
}
};
int main()
{
LinkedList a1;
a1.insertFront(5);
a1.insertFront(6);
a1.insertFront(7);
a1.PrintLinkedList();
std::cin.get();
}
As you will see in the screenshots in the watch1 tab the this->head_ref preserves the location of the Node* but Node* i.e. (*(this->head_ref)) doesn't preserve the location of the Node. I want to know what is causing this. Is it because Node** head_ref has no regulation in how the inside pointer points to the Node or is it a scope problem? The problem occurs each time right after the next function call happens and the debugger enters the insertFront function, the Node* becomes a free pointer pointing to nothing.
First call screenshot
Second call screenshot before entering insertFront
Second call screenshot just after entering insertFront but a new Node object has not been made yet
The answer is provided by #IgorTandetnik in the comments.
The Node object is allocated on the heap. But the Node* object named new_node is allocated on the stack. You have head_ref point to new_node and new_node point to the Node object. Then the function returns, new_node is gone, and there is no longer any connection between head_ref and the heap-allocated Node. head_ref points to some garbage value where new_node used to be, and Node on the heap is leaked as nothing points to it anymore.
I have changed the code accordingly by using Node* head_ref which will refer to a heap allocated Node instead of the new_nodepointer which goes out of scope.
#include<iostream>
#define print(x) std::cout<<x<<std::endl;
class Node
{
public:
int data;
Node* next;
};
class LinkedList
{
private:
Node* head_ref;
public:
LinkedList() :head_ref(NULL) {};
void insertFront(int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
if(this->head_ref == NULL)
this->head_ref = new_node;
else
{
new_node->next = this->head_ref;
this->head_ref = new_node;
}
}
void PrintLinkedList()
{
Node* temp = this->head_ref;
while (temp->next != NULL)
{
print(temp->data);
temp = temp->next;
}
print(temp->data);
print("\n");
}
};
int main()
{
LinkedList a1;
a1.insertFront(5);
a1.insertFront(6);
a1.insertFront(7);
a1.PrintLinkedList();
std::cin.get();
}
I am trying to create a single linked list but the above code is giving an error: segmentation fault core dumped. I am inserting elements 5,9,12 in the singlelinkedlist and displaying the list. First I create a node and then class singlelinkedlist with all the methods. I am still trying to learn basics.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node()
{
}
Node(int element)
{
data = element;
next=NULL;
}
Node(int element, Node* link)
{
data = element;
next = link;
}
};
class SingleLinkedList
{
public:
Node* head;
int listsize = 0;
Node* curr;
bool isempty()
{
return head==NULL;
}
void Insert(int data)
{
Node* new_node = new Node(data);
if(isempty())
{
head = new_node;
listsize++;
return;
}
curr = head;
while(curr->next!=NULL)
{
curr->next=curr;
}
curr->next=new_node;
listsize++;
}
void display()
{
curr = head;
while(curr!=NULL)
{
cout<<curr->data<<"-->";
curr=curr->next;
}
}
};
int main()
{
SingleLinkedList l1;
l1.Insert(5);
l1.Insert(9);
l1.Insert(12);
l1.display();
}
Try to change:
while (curr->next != NULL)
{
curr->next = curr;
}
to:
while (curr->next != NULL)
{
curr = curr->next;
}
for you list traversal while doing node insertion to avoid infinite loop
The pointer head is not initialized. Its value is not garanteed to be nullptr. Your code is therefore UB, since the first insert in the list will invoke isempty(), which is using this uninitialised pointer.
When this is done, consider also Anon’s answer.
I am trying to implement a linked list in C++. I have the following code
class LinkedList {
private:
struct node {
int data;
node* next;
}*
head;
node* mkNode(int data, node* next){
node* n;
n->data = data;
n->next = next;
return n;
}
public:
LinkedList(){
head = NULL;
}
void insertAtHead(int data){
head = mkNode(data, head);
}
};
I am getting a segmentation fault: 11 on the lines n->data = data; and n->next = next; inside the mkNode() function. any idea why?
node* mkNode(int data, node* next)
{
node* n;
n->data = data;
n->next = next;
return n;
}
pointer 'n' to 'node' is not initialized. Try to initialize it with struct node memory.
node* n = new struct node;
Your pointer is not initialized.
Creating an Object on heap will solve this, don't forget to free the memory after use.
node* mkNode(int data, node* next){ return new node({data,next}); }
I have made a simple linkedlist implementation and I am getting this error on when I am running the code at Insert() function call in Main(), I dont understand Why so.
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node* head;
int main(){
head=NULL;
Insert(1,2);
Insert(2,1);
Insert(3,1);
Insert(4,1);
}
void Print(){
struct Node* temp;
temp=head;
while(temp!=NULL){
printf("%d ",tenp->data);
temp=temp->next;
}
printf("\n");
}
Node* Insert(Node *head,int data)
{
Node *node = new Node();
node->data = data; // ASSIGNING VALUES TO NEW NODE
node->next = NULL; // ALSO AS TO ACT AS THE TAIL NODE ADDING THE null VALUE AT THE NEXT POINTER
if(head == NULL) // CASE: WHEN LIST IS EMPTY
return node;
Node *temp = head; // dereferencing value for TEMP, assignning it the HEAD values, HEAD is the current tail node
while(temp->next != NULL) // Traversing till 1 before
temp = temp->next;
temp->next = node; // making the last move, assigning the LINK to new node.
return head; // returinng the funn call with VALUE
}
Insert(1,2)//this won't work as insert()
//expects node* type and not an integer as first argument.
You should pass the pointer to head instead of the value.
You are passing 1,2,3 and 4 into a Node* argument.
You have to pass the actual head node and assign the result,
head = Insert( head, value );
Thats how you made the function to be used.