When i write this line: cout<< "LOOK AT HERE PLEASE"; at the function 'insert' the program gives me this output: 1 0 but when erase the line the program gives me this output: 1 2.
Why this is happening?
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void initNode(struct Node *head, int n){
head->data = n;
head->next = NULL;
}
void insert(struct Node *head,int n){
Node no;
Node *novo = &no;
novo->data = n;
novo->next = NULL;
Node *cur = head;
while(cur){
if(cur->next == NULL){
cur->next = novo;
return;
}
cout<< "LOOK AT HERE PLEASE";
cur = cur->next;
}
}
void display(struct Node *head){
Node *list = head;
while(list){
cout<<list->data<< " "<<endl;
list = list->next;
}
cout<<endl<<endl;
}
int main(){
Node head;
initNode(&head,1);
insert(&head,2);
display(&head);
}
Change
Node no;
Node *novo = &no;
To
Node *novo = new Node;
Stuff on the stack have short lives.
You then need to figure out how to prevent memory leaks (delete it somewhere!)
What you did in the following code
void insert(struct Node *head,int n){
Node no;
Node *novo = &no;
...
Node *cur = head;
while(cur){
if(cur->next == NULL){
cur->next = novo;
return;
}
is return a pointer to a local variable, which is undefined behavior.
You can fix it, as already pointed out by #ed-heal, by
Node *novo = new Node;
which will allocate a Node dynamically.
Related
When I assign the link list head (of type pointer to struct) to another temporary head (of the same type), I get the segmentation error. Can someone please help me with this?
I am using below online compiler to run this code.
https://www.programiz.com/cpp-programming/online-compiler/
https://www.onlinegdb.com/online_c++_compiler
#include <iostream>
using namespace std;
struct Node{
int val;
Node *next;
};
Node* newNode(int val){
Node *newNode = new Node;
newNode->val = val;
newNode->next = nullptr;
return newNode;
}
Node* addNode(Node *head, int val){
if(head == nullptr){
return newNode(val);
}
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = newNode(val);
return head;
}
void printList(Node *head){
while(head){
cout<<head->val<<" ";
head = head->next;
}
cout<<endl;
}
int main() {
Node *head;
head = addNode(head, 1);
head = addNode(head, 2);
head = addNode(head, 3);
head = addNode(head, 4);
head = addNode(head, 5);
head = addNode(head, 6);
head = addNode(head, 7);
printList(head);
//If comment out, then no segmentation fault
Node *head1 = head; //Segmentation fault
return 0;
}
In main(), change Node *head; to Node *head = nullptr;. Your code has undefined behavior when the 1st call to addNode() tries to evaluate an uninitialized pointer.
Everything else looks OK.
I am trying to code for deletion of a node with k as data of linked list. The below program is running fine, but it is not giving desired output if we have to delete the head node. For example, if the linked list is 98->6->1 and I have to delete 98, then the output which the program is showing is 0->6->1. Except for the deletion of the head node, it is working correctly for all other cases.
Below is the c++ code for the same.
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
Node * insert(Node* head, int data) {
Node* new_node= new Node();
new_node->data = data;
new_node->next = head;
head = new_node;
return head;
}
void deleteNode(Node *head, int key)
{
Node *temp = head;
Node *prev = NULL;
if(temp!=NULL && temp->data==key){
head = temp->next;
delete temp;
}
else{
while(temp!=NULL && temp->data!=key){
prev = temp;
temp = temp->next;
}
if(temp == NULL){
return;
}
prev->next = temp->next;
delete temp;
}
}
void display(Node * head) {
while(head != NULL)
{
cout<<head->data<<" ";
head = head->next;
}
}
int main() {
Node * head = NULL;
head = insert(head, 1);
head=insert(head,6);
head=insert(head,98);
deleteNode(head,98);
display(head);
return 0;
}
In deleteNode(), you are passing in the head node by value, so any modification made to it is not reflected back to the caller. You need to either return the new head, like you do with Insert(), or else you need to pass in the head by reference:
void deleteNode(Node* &head, int key)
The mistake in your code is that the head you are passing to deleteNode function is by value so the changes made to the head function is not displayed. The head in your function is not the same head in your main function it is just the copy of that head, so to apply the same change being applied to the head in deletenode function to the original head, you have to pass the address of the head(or pass by reference).
Editing in your code-
I have applied changes in deleteNode function first five lines and the third last line when you are passing value by reference deleteNode(&head,98);
Edited code-
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* next;
};
Node * insert(Node* head, int data) {
Node* new_node= new Node();
new_node->data = data;
new_node->next = head;
head = new_node;
return head;
}
void deleteNode(Node **head, int key)
{
Node *temp = *head;
Node *prev = NULL;
if(temp!=NULL && temp->data==key){
*head = temp->next;
temp->next = NULL;
delete temp;
}
else{
while(temp!=NULL && temp->data!=key){
prev = temp;
temp = temp->next;
}
if(temp == NULL){
return;
}
prev->next = temp->next;
// temp->next = NULL;
delete temp;
}
}
void display(Node * head) {
while(head != NULL)
{
cout<<head->data<<" ";
head = head->next;
}
}
int main() {
Node * head = NULL;
head = insert(head, 1);
head=insert(head,6);
head=insert(head,98);
deleteNode(&head,98);
display(head);
return 0;
}
Now if you run the above code the output you will get after deleting node of value 98 will be 6->1.
Hope you will find it helpful.
The following code works fine:
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
Node(int data, Node *next = nullptr){
this->data = data;
this->next = next;
}
};
void push_back(Node **head, int data){
if(*head == nullptr){
*head = new Node(data);
}
else{
Node *current = *head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
void Print(Node **head){
Node *current = *head;
while(current != nullptr){
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main(){
Node *head = nullptr;
push_back(&head, 5);
push_back(&head, 2);
push_back(&head, 1);
push_back(&head, -7);
Print(&head);
}
But when I try that bellow, nothing happens and head remains nullptr along with all the operations.
All I did was that I passed single pointers to function instead of double pointers:
#include <iostream>
using namespace std;
struct Node{
int data;
struct Node *next;
Node(int data, Node *next = nullptr){
this->data = data;
this->next = next;
}
};
void push_back(Node *head, int data){
if(head == nullptr){
head = new Node(data);
}
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
void Print(Node *head){
Node *current = head;
while(current != nullptr){
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main(){
Node *head = nullptr;
push_back(head, 5);
push_back(head, 2);
push_back(head, 1);
push_back(head, -7);
Print(head);
}
I don't understand why do I need double pointers to make it work?
Is the second program only sending a copy of head to the functions and nothing more?
void push_back(Node *head, int data){
if(head == nullptr){
head = new Node(data);
}
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
you can't change the value of pointer head by push_back in main function. We can change a object by passing its pointer or reference to another function, but not by passing itself! So each time head = new Node(data);(try to change head) actually not change head in the function which called push back() and caused memory overflow
I am about to create a linked that can insert and display until now:
struct Node {
int x;
Node *next;
};
This is my initialisation function which only will be called for the first Node:
void initNode(struct Node *head, int n){
head->x = n;
head->next = NULL;
}
To add the Node, and I think the reason why my linked list isn't working correct is in this function:
void addNode(struct Node *head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
My main function:
int _tmain(int argc, _TCHAR* argv[])
{
struct Node *head = new Node;
initNode(head, 5);
addNode(head, 10);
addNode(head, 20);
return 0;
}
Let me run the program as I think it works. First I initialise the head Node as a Node like this:
head = [ 5 | NULL ]
Then I add a new node with n = 10 and pass head as my argument.
NewNode = [ x | next ] where next points at head. And then I change the place where head is pointing to NewNode, since NewNode is the first Node in LinkedList now.
Why isn't this working? I would appreciate any hints that could make me move in the right direction. I think LinkedList is a bit hard to understand.
When I'm printing this, it only returns 5:
This is the most simple example I can think of in this case and is not tested. Please consider that this uses some bad practices and does not go the way you normally would go with C++ (initialize lists, separation of declaration and definition, and so on). But that are topics I can't cover here.
#include <iostream>
using namespace std;
class LinkedList{
// Struct inside the class LinkedList
// This is one node which is not needed by the caller. It is just
// for internal work.
struct Node {
int x;
Node *next;
};
// public member
public:
// constructor
LinkedList(){
head = NULL; // set head to NULL
}
// destructor
~LinkedList(){
Node *next = head;
while(next) { // iterate over all elements
Node *deleteMe = next;
next = next->next; // save pointer to the next element
delete deleteMe; // delete the current entry
}
}
// This prepends a new value at the beginning of the list
void addValue(int val){
Node *n = new Node(); // create new Node
n->x = val; // set value
n->next = head; // make the node point to the next node.
// If the list is empty, this is NULL, so the end of the list --> OK
head = n; // last but not least, make the head point at the new node.
}
// returns the first element in the list and deletes the Node.
// caution, no error-checking here!
int popValue(){
Node *n = head;
int ret = n->x;
head = head->next;
delete n;
return ret;
}
// private member
private:
Node *head; // this is the private member variable. It is just a pointer to the first Node
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
cout << list.popValue() << endl;
cout << list.popValue() << endl;
cout << list.popValue() << endl;
// because there is no error checking in popValue(), the following
// is undefined behavior. Probably the program will crash, because
// there are no more values in the list.
// cout << list.popValue() << endl;
return 0;
}
I would strongly suggest you to read a little bit about C++ and Object oriented programming. A good starting point could be this: http://www.galileocomputing.de/1278?GPP=opoo
EDIT: added a pop function and some output. As you can see the program pushes 3 values 5, 10, 20 and afterwards pops them. The order is reversed afterwards because this list works in stack mode (LIFO, Last in First out)
You should take reference of a head pointer. Otherwise the pointer modification is not visible outside of the function.
void addNode(struct Node *&head, int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode -> next = head;
head = NewNode;
}
I'll join the fray. It's been too long since I've written C. Besides, there's no complete examples here anyway. The OP's code is basically C, so I went ahead and made it work with GCC.
The problems were covered before; the next pointer wasn't being advanced. That was the crux of the issue.
I also took the opportunity to make a suggested edit; instead of having two funcitons to malloc, I put it in initNode() and then used initNode() to malloc both (malloc is "the C new" if you will). I changed initNode() to return a pointer.
#include <stdlib.h>
#include <stdio.h>
// required to be declared before self-referential definition
struct Node;
struct Node {
int x;
struct Node *next;
};
struct Node* initNode( int n){
struct Node *head = malloc(sizeof(struct Node));
head->x = n;
head->next = NULL;
return head;
}
void addNode(struct Node **head, int n){
struct Node *NewNode = initNode( n );
NewNode -> next = *head;
*head = NewNode;
}
int main(int argc, char* argv[])
{
struct Node* head = initNode(5);
addNode(&head,10);
addNode(&head,20);
struct Node* cur = head;
do {
printf("Node # %p : %i\n",(void*)cur, cur->x );
} while ( ( cur = cur->next ) != NULL );
}
compilation: gcc -o ll ll.c
output:
Node # 0x9e0050 : 20
Node # 0x9e0030 : 10
Node # 0x9e0010 : 5
Below is a sample linkedlist
#include <string>
#include <iostream>
using namespace std;
template<class T>
class Node
{
public:
Node();
Node(const T& item, Node<T>* ptrnext = NULL);
T value;
Node<T> * next;
};
template<class T>
Node<T>::Node()
{
value = NULL;
next = NULL;
}
template<class T>
Node<T>::Node(const T& item, Node<T>* ptrnext = NULL)
{
this->value = item;
this->next = ptrnext;
}
template<class T>
class LinkedListClass
{
private:
Node<T> * Front;
Node<T> * Rear;
int Count;
public:
LinkedListClass();
~LinkedListClass();
void InsertFront(const T Item);
void InsertRear(const T Item);
void PrintList();
};
template<class T>
LinkedListClass<T>::LinkedListClass()
{
Front = NULL;
Rear = NULL;
}
template<class T>
void LinkedListClass<T>::InsertFront(const T Item)
{
if (Front == NULL)
{
Front = new Node<T>();
Front->value = Item;
Front->next = NULL;
Rear = new Node<T>();
Rear = Front;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
newNode->next = Front;
Front = newNode;
}
}
template<class T>
void LinkedListClass<T>::InsertRear(const T Item)
{
if (Rear == NULL)
{
Rear = new Node<T>();
Rear->value = Item;
Rear->next = NULL;
Front = new Node<T>();
Front = Rear;
}
else
{
Node<T> * newNode = new Node<T>();
newNode->value = Item;
Rear->next = newNode;
Rear = newNode;
}
}
template<class T>
void LinkedListClass<T>::PrintList()
{
Node<T> * temp = Front;
while (temp->next != NULL)
{
cout << " " << temp->value << "";
if (temp != NULL)
{
temp = (temp->next);
}
else
{
break;
}
}
}
int main()
{
LinkedListClass<int> * LList = new LinkedListClass<int>();
LList->InsertFront(40);
LList->InsertFront(30);
LList->InsertFront(20);
LList->InsertFront(10);
LList->InsertRear(50);
LList->InsertRear(60);
LList->InsertRear(70);
LList->PrintList();
}
Both functions are wrong. First of all function initNode has a confusing name. It should be named as for example initList and should not do the task of addNode. That is, it should not add a value to the list.
In fact, there is not any sense in function initNode, because the initialization of the list can be done when the head is defined:
Node *head = nullptr;
or
Node *head = NULL;
So you can exclude function initNode from your design of the list.
Also in your code there is no need to specify the elaborated type name for the structure Node that is to specify keyword struct before name Node.
Function addNode shall change the original value of head. In your function realization you change only the copy of head passed as argument to the function.
The function could look as:
void addNode(Node **head, int n)
{
Node *NewNode = new Node {n, *head};
*head = NewNode;
}
Or if your compiler does not support the new syntax of initialization then you could write
void addNode(Node **head, int n)
{
Node *NewNode = new Node;
NewNode->x = n;
NewNode->next = *head;
*head = NewNode;
}
Or instead of using a pointer to pointer you could use a reference to pointer to Node. For example,
void addNode(Node * &head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
}
Or you could return an updated head from the function:
Node * addNode(Node *head, int n)
{
Node *NewNode = new Node {n, head};
head = NewNode;
return head;
}
And in main write:
head = addNode(head, 5);
The addNode function needs to be able to change head. As it's written now simply changes the local variable head (a parameter).
Changing the code to
void addNode(struct Node *& head, int n){
...
}
would solve this problem because now the head parameter is passed by reference and the called function can mutate it.
head is defined inside the main as follows.
struct Node *head = new Node;
But you are changing the head in addNode() and initNode() functions only. The changes are not reflected back on the main.
Make the declaration of the head as global and do not pass it to functions.
The functions should be as follows.
void initNode(int n){
head->x = n;
head->next = NULL;
}
void addNode(int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode->next = head;
head = NewNode;
}
I think that, to make sure the indeep linkage of each node in the list, the addNode method must be like this:
void addNode(struct node *head, int n) {
if (head->Next == NULL) {
struct node *NewNode = new node;
NewNode->value = n;
NewNode->Next = NULL;
head->Next = NewNode;
}
else
addNode(head->Next, n);
}
Use:
#include<iostream>
using namespace std;
struct Node
{
int num;
Node *next;
};
Node *head = NULL;
Node *tail = NULL;
void AddnodeAtbeggining(){
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL)
{
head = temp;
tail = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void addnodeAtend()
{
Node *temp = new Node;
cout << "Enter the item";
cin >> temp->num;
temp->next = NULL;
if (head == NULL){
head = temp;
tail = temp;
}
else{
tail->next = temp;
tail = temp;
}
}
void displayNode()
{
cout << "\nDisplay Function\n";
Node *temp = head;
for(Node *temp = head; temp != NULL; temp = temp->next)
cout << temp->num << ",";
}
void deleteNode ()
{
for (Node *temp = head; temp != NULL; temp = temp->next)
delete head;
}
int main ()
{
AddnodeAtbeggining();
addnodeAtend();
displayNode();
deleteNode();
displayNode();
}
In a code there is a mistake:
void deleteNode ()
{
for (Node * temp = head; temp! = NULL; temp = temp-> next)
delete head;
}
It is necessary so:
for (; head != NULL; )
{
Node *temp = head;
head = temp->next;
delete temp;
}
Here is my implementation.
#include <iostream>
using namespace std;
template< class T>
struct node{
T m_data;
node* m_next_node;
node(T t_data, node* t_node) :
m_data(t_data), m_next_node(t_node){}
~node(){
std::cout << "Address :" << this << " Destroyed" << std::endl;
}
};
template<class T>
class linked_list {
public:
node<T>* m_list;
linked_list(): m_list(nullptr){}
void add_node(T t_data) {
node<T>* _new_node = new node<T>(t_data, nullptr);
_new_node->m_next_node = m_list;
m_list = _new_node;
}
void populate_nodes(node<T>* t_node) {
if (t_node != nullptr) {
std::cout << "Data =" << t_node->m_data
<< ", Address =" << t_node->m_next_node
<< std::endl;
populate_nodes(t_node->m_next_node);
}
}
void delete_nodes(node<T>* t_node) {
if (t_node != nullptr) {
delete_nodes(t_node->m_next_node);
}
delete(t_node);
}
};
int main()
{
linked_list<float>* _ll = new linked_list<float>();
_ll->add_node(1.3);
_ll->add_node(5.5);
_ll->add_node(10.1);
_ll->add_node(123);
_ll->add_node(4.5);
_ll->add_node(23.6);
_ll->add_node(2);
_ll->populate_nodes(_ll->m_list);
_ll->delete_nodes(_ll->m_list);
delete(_ll);
return 0;
}
link list by using node class and linked list class
this is just an example not the complete functionality of linklist, append function and printing a linklist is explained in the code
code :
#include<iostream>
using namespace std;
Node class
class Node{
public:
int data;
Node* next=NULL;
Node(int data)
{
this->data=data;
}
};
link list class named as ll
class ll{
public:
Node* head;
ll(Node* node)
{
this->head=node;
}
void append(int data)
{
Node* temp=this->head;
while(temp->next!=NULL)
{
temp=temp->next;
}
Node* newnode= new Node(data);
// newnode->data=data;
temp->next=newnode;
}
void print_list()
{ cout<<endl<<"printing entire link list"<<endl;
Node* temp= this->head;
while(temp->next!=NULL)
{
cout<<temp->data<<endl;
temp=temp->next;
}
cout<<temp->data<<endl;;
}
};
main function
int main()
{
cout<<"hello this is an example of link list in cpp using classes"<<endl;
ll list1(new Node(1));
list1.append(2);
list1.append(3);
list1.print_list();
}
thanks ❤❤❤
screenshot https://i.stack.imgur.com/C2D9y.jpg
I don't understand why the display() func show me only the first member of the list. I think I did a mess with pointers, but I can't understand where. I have compared this to other linked list source and it seem that the function is written in the-good-way.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
struct Node
{
int Data;
Node * next;
};
void initNode(struct Node *head,int n);
void AddNode(int n,Node* head);
void display(Node* head);
int main()
{
Node * head = new Node;
initNode(head,5);
display(head);
AddNode(10,head);
display(head);
AddNode(15,head);
display(head);
cin.get();
return 0;
}
void AddNode(int n,Node * head)
{
Node * node = new Node;
node->Data = n;
node->next = NULL;
Node * nextNode = head;
while(nextNode)
{
if(nextNode->next == NULL)
{
nextNode->next = node;
}
nextNode = nextNode->next;
}
}
void display(Node * head)
{
while(head)
{
cout << head->Data << " "<<endl;
head = head->next;
}
}
void initNode(struct Node *head,int n)
{
head->Data = n;
head->next = NULL;
}
Your AddNode method is over-complicated. Do something like this to add to the front:
Node *AddNode(int n, Node *head)
{
Node *newNode = new Node;
newNode->Data = n;
newNode->next = head;
return newNode;
}
Or to add to the end:
Node *AddNode(int n, Node *head)
{
Node *newNode = new Node;
newNode->Data = n;
newNode->next = NULL;
if(head == NULL) return newNode;
Node *current = head;
while(current->Next != NULL)
{
current = current->Next;
}
current->Next = newNode;
return head;
}
Doing AddNode this way you will not need initNode. Now you can just day:
Node *head = NULL;
head = AddNode(5, head);
head = AddNode(10, head);
head = AddNode(15, head);
display(head);
Also, you don't need to say struct Node in C++, it is only required in C.
Function AddNode has an infinite loop.
void AddNode(int n,Node * head)
{
Node * node = new Node;
node->Data = n;
node->next = NULL;
Node * nextNode = head;
while(nextNode)
{
if(nextNode->next == NULL)
{
nextNode->next = node;
}
nextNode = nextNode->next;
}
}
Let assume that you have only one element that is the head (after a call of initNode). And as the result head->next = NULL. So inside the body of the loop you make assignment
nextNode->next = node;
Now head->next is not equal to NULL. So after statement
nextNode = nextNode->next;
nextNode caontains the new element. As it is not equal to NULL then iteration of the loop will be repeated. Again for the new node its data member next is equal to NULL. And you add it to it itself.
Now you have no any element in the list that would have data member next equal to NULL. So you are unable to add new elements. The last element contains reference to itself.
You could write the function the following way
void AddNode(int n,Node * head)
{
Node * node = new Node;
node->Data = n;
node->next = NULL;
Node * nextNode = head;
while( nextNode -> next ) nextNode = nextNode->next;
nextNode->next = node;
}
But take into account that it is assumed that head is not equal to NULL. otherwise the function will be incorrect. I think that you should redesign you list.
In your AddNode function add a break in the if block.
void AddNode(int n,Node * head)
{
Node * node = new Node;
node->Data = n;
node->next = NULL;
Node * nextNode = head;
while(nextNode)
{
if(nextNode->next == NULL)
{
nextNode->next = node;
break;
}
nextNode = nextNode->next;
}
}
Now it should add properly.
Node * nextNode = head;
while(nextNode)
{
if(nextNode->next == NULL)
{
nextNode->next = node;
}
nextNode = nextNode->next;
}
The problem is this block of code. When you find the end of the list (if nextNode->next == NULL) you need to break out of the loop. Try it with an example to convince yourself.
Each time you add a node you traverse from head to the end of the list
You can change it as follows
void AddNode(int n){
Node *node=new Node;
node->data=n;
node->next=NULL; //head is global
if(head==NULL){
t=head=n;
}
else{
t->next=n; //t is global
t=t->next;
}
}