Good day,
I have a sample LinkedList, which is a very basic class for me to learn C++ with.
At the moment i'm trying to add new nodes to my linked list using a class etc, and I encountered a very odd bug.
Here's my LinkedList.h:
struct Node {
Node* next;
int value;
};
class LinkedList {
private:
Node* root;
public:
LinkedList();
void print();
void add(int val);
~LinkedList();
};
And here's my LinkedList.cpp
#include "LinkedList.h"
#include <iostream>
using namespace std;
LinkedList::LinkedList() {
root = NULL;
}
LinkedList::~LinkedList() {
}
void LinkedList::add(int val) {
Node node;
node.next = NULL;
node.value = val;
if (root != NULL)
node.next = root;
root = &node;
cout << root->value << endl; // TEST PRINT 1
}
void LinkedList::print() {
cout << root->value <<endl; // TEST PRINT 2
}
This is my main.cpp:
#include "LinkedList.h"
#include <iostream>
using namespace std;
int main() {
LinkedList list;
list.add(5);
list.print();
}
This code should simply create a new node with the value '5' and make it the root. When I add a new number a different node should be created and this new node should be the root with the old root as its 'next' node.
I have two debug messages, located near 'TEST PRINT 1' and 'TEST PRINT 2'. Both lines are exactly the same, yet the first print gives me the correct value (which is 5) while the second print gives me a very weird negative number (-858993460).
What have I done wrong?
The problem is here:
root = &node;
Here you make root point to the local variable node. The local variable which will go out of scope and be destructed once the function returns.
You need to allocate nodes dynamically.
Related
So I've been working on a linked list in C++ through a header file. When I insert values into it, it works fine, but as soon as I return to the main class and try to print the value stored inside a node, it returns a negative number. Here is an excerpt of my code so far, I tried to keep it as simplistic as possible.
This is the header file that contains the code for the linked list.
#pragma once
#include <iostream>
using namespace std;
template <typename T>
class LinkedList {
public:
struct Node {
T data;
struct Node* next;
};
Node* head;
void AddHead(const T& addData) {
Node n;
n.data = addData;
n.next = head;
head = &n;
Print();
}
void Print() {
cout << head << " " << (*head).data << endl;
}
private:
};
And here is the reference from main.
LinkedList<int> l = LinkedList<int>();
int i = 5;
l.AddHead(i);
l.Print();
Now I thought this would work fine, but apparently something happens between when the node is added, when the program returns out of the header file, and when it prints again. I put in a second print statement inside to show the difference.
As it stands the output looks like this:
0000004F9A8FF7F8 5
0000004F9A8FF7F8 -1464607816
So at the same memory address, the value stored inside changes? I don't know what I'm doing wrong and I appreciate any help.
void AddHead(const T& addData) {
Node n;
n.data = addData;
n.next = head;
head = &n;
Print();
}
Once AddHead ends n is released, its a temorary variable on the stack. You have to create the nodes on the heap
void AddHead(const T& addData) {
Node *n = new Node();
n->data = addData;
n->next = head;
head = n;
Print();
}
And next advice. dont use naked pointers, use std::shared_ptr or std::unique_ptr.
I am trying to delete Nodes from a given point but I am stuck on how to delete the last node. Nodes other than tail can be deleted by swapping the values and changing the links.
My Code:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
void appointNULL(Node *point)
{
point = NULL;
}
int main()
{
Node *head = new Node(10);
head->next = new Node(20);
appointNULL(head->next);
cout<<head->next->data;
}
Output:
20
when I tried to print it came out same without any change?
what am I doing wrong?
I'm trying to represent a singly linked list in C++. I'm adding two elements at the head of the list, 4 and 34. I also have a print method, to print the contents of the linked list.
I have an incorrect head update somewhere, because the print method enters an infinite loop. I tried debugging with breakpoints, and that lead me down the following rabbit hole:
During the second insertion: s.insert(34), I somehow change the value of head to 34, when creating a node for 34. Can someone help me understand how that happened?
Or am I missing the picture entirely? Any help would be greatly appreciated!
#include <vector>
#include <iostream>
using namespace std;
class Node {
public:
Node* next;
int key;
Node(int k) : key(k), next(nullptr) {}; //on s.insert(34), this changes head to 34
};
class SinglyLinkedList {
public:
Node* head;
SinglyLinkedList() : head(nullptr) {};
void insert(int);
void print();
};
void SinglyLinkedList::insert(int x) {
Node n = Node(x);
if (head == nullptr) {
head = &n;
}
else {
n.next = head; // head already points to 34 at this point
head = &n;
}
}
void SinglyLinkedList::print() {
for (Node *i = this->head; i != nullptr; i = i->next)
cout << i->key << endl;
}
int main(){
SinglyLinkedList s = SinglyLinkedList();
s.insert(4);
s.insert(34);
s.print();
}
So I'm working on a college project where I need to create a linked list of 'Structures'. and when I'm adding a new element to the linked list I get this error, which is weird because I am not even using the stack while doing it.
Here's how 'Structure' is defined:
#ifndef Structure_h
#define Structure_h
#include <stack>
using namespace std;
class Structure
{
public:
int Integer;
stack <int> s;
};
#endif
Definition of node:
#pragma once
#ifndef Node_h
#define Node_h
using namespace std;
#include "Structure.h"
class Node
{
public:
Node();
Structure Str;
Node *next;
};
#endif
LinkedList.h:
#pragma once
#ifndef LinkedList_h
#define LinkedList_h
using namespace std;
#include "Node.h"
class LinkedList
{
public:
LinkedList();
int size;
void add(int a);
Node *Current;
Node *Start;
};
#endif
LinkedList.cpp:
#include "LinkedList.h"
#include <iostream>
LinkedList::LinkedList()
{
Node FirstNode;
Start = Current = &FirstNode;
cout << "Start = " << Start->Str.Integer << endl;
cout << "Current = " << Current->Str.Integer << endl;
}
void LinkedList::add(int a)
{
Node n;
n.Str.Integer = a;
Current->next = &n;
Current = Current->next;
cout << Current->Str.Integer;
}
Now whenever I create a new LinkedList and adding something to it I get this error.
I got a feeling like I'm using the Stack wrong somehow, not sure why though.
Thank you from advance.
In this method:
void LinkedList::add(int a)
{
Node n;
n.Str.Integer = a;
Current->next = &n;
Current = Current->next;
cout << Current->Str.Integer;
}
you are adding as next local variable n, it will get destroyed once add returns. This is undefined behaviour. You should use Node* n = new Node;, dont forget to deallocate.
[edit]
The same applies to other places in your code where you take a pointer to local variable and store it as a list node.
You have:
void LinkedList::add(int a)
{
Node n;
n.Str.Integer = a;
Current->next = &n;
// Here, you are storing a pointer to a local variable.
// The pointer becomes a dangling pointer when the function returns.
Current = Current->next;
cout << Current->Str.Integer;
}
Use a dynamically allocated Node.
void LinkedList::add(int a)
{
Node* n = new Node;
n->Str.Integer = a;
Current->next = n;
Current = Current->next;
cout << Current->Str.Integer;
}
So for my assignment, I am supposed to implement a Node class that just contains data and pointers to its two siblings and a BinaryTree that reads in these Nodes and creates a binary tree out of them. My problem is pointing to the root of the Tree does not seem to work. Any help you can provide would be appreciated!
Note: The error is found a few lines into the addNode method in the BinaryTree.cpp file which can be found at the end of the question. Also, I am not able to access the value of size either, so I believe this is some sort of weird scope issues I cannot resolve. I also cannot use the "this" keyword in the addNode function.
I am also not allowed to use structs, per my homeworks' instruction.
Node.H
#include <iomanip>
using namespace std;
class Node
{
public:
int data;
Node* leftChild;
Node* rightChild;
Node(int data, Node* leftChild, Node* rightChild);
};
Node.cpp
#include <iomanip>
#include <iostream>
#include "Node.h"
using namespace std;
Node::Node(int data, Node* leftChild, Node* rightChild)
{
this->data = data;
this->leftChild = leftChild;
this->rightChild = rightChild;
}
BinaryTree.H
#include <iomanip>
#include "Node.h"
using namespace std;
class Tree
{
public:
Tree(int data);
void addNode(int data);
void inOrder(Node* N);
protected:
Node* root;
int size;
int data;
private:
int printNode(Node* N);
};
BinaryTree.cpp
#include <iostream>
#include <iomanip>
#include "BinaryTree.h"
using namespace std;
//Tree constructor. Sets the values of data, size, and root.
Tree::Tree(int data)
{
this->data = data;
this->size = 0;
this->root = new Node(data, NULL, NULL);
}
//Adds a node to the current Tree.
void addNode(int data)
{
Node* tempNode = new Node(data, NULL, NULL);
Node* current = root; //THIS IS THE ERROR LINE.
while(current!=NULL)
{
//If the data we are trying to add is already in the Tree
if(current->data == tempNode->data)
{
cout << "Data already in the Tree.";
}
//If the data for the new node is larger than the old
else if(current->data < tempNode->data)
{
//See if the right child is null. If so, add the tree node there.
if(current->rightChild == NULL)
{
current->rightChild = tempNode;
return;
}
//Otherwise, traverse down the right tree.
else
{
current = current->rightChild;
}
}
//The data is smaller than the current node
else
{
//See if the left child is null. If so, add the tree node there.
if(current->leftChild == NULL)
{
current->leftChild = tempNode;
return;
}
//Otherwise, traverse down the left tree
else
{
current = current->leftChild;
}
}//End of leftChild Else
}//End of while
}//End of addNode
void addNode(int data)
should be:
void Tree::addNode(int data)
as it is a member function of class Tree
//Adds a node to the current Tree.
void addNode(int data)
Should be:
//Adds a node to the this Tree
void Tree::addNode(int data)