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;
}
Related
So I was doing a linked list assignment where given two numbers in a linked list form, add the numbers up and make the final answer in a linked list form. I keep getting an "undeclared identifier" error for my code and I was wondering how to fix it.
Error message:
List.cpp:48:3: error: use of undeclared identifier 'append'
append(h, c);
Thanks.
#include <iostream>
#ifndef LISTNODE_H
#define LISTNODE_H
using namespace std;
class ListNode {
public:
ListNode();
ListNode(int value, ListNode* next);
int value;
ListNode *next;
private:
friend class List;
};
#endif
#include <iostream>
#include "ListNode.h"
using namespace std;
ListNode:: ListNode() {
value = 'b';
next = NULL;
}
#include <iostream>
#include "ListNode.h"
#include <vector>
#ifndef LIST_H
#define LIST_H
using namespace std;
class List {
public:
List();
void append(ListNode* node, vector<char> c);
ListNode *head;
};
#endif
#include <iostream>
#include <string>
#include "List.h"
#include <vector>
#include "ListNode.h"
using namespace std;
void List:: append(ListNode *node, vector<char> c) {
//ListNode *temp
for(int i = 0; i < c.size(); i++) {
if(head == NULL) {
head = node;
}
else {
ListNode* itr = head;
while(itr -> next != NULL) {
itr = itr -> next;
}
node = itr -> next;
node -> value = c[i];
cout << node -> value << endl;
}
}
}
List:: List() { //Initializes the head and the tail for the whole class
head = NULL;
}
int main() {
ListNode *h;
string num1, num2, sentence;
vector<char> c;
cout << "Type in two numbers" << endl;
cout << "Number 1: " << endl;
cin >> num1;
cout << "Number 2: " << endl;
cin >> num2;
//cout << "Type in a sentence: " << endl;
//cin >> sentence;
cout << "--------" << endl;
for(int i = 0; i < num1.size(); i++) {
c.push_back(num1[i]);
}
append(h, c);
return 0;
}
This code:
append(h, c);
calls a free function named append. But there is no such function in your code.
You do have an append function inside the List class, but that's a member function, so you need a List object to call that function on. So you'll need something like:
List l;
l.append(h, c);
You defined the member function append in the class List (that (the function) by the way does not make any sense)
void List:: append(ListNode *node, vector<char> c) {
//...
}
But inside main you are calling a stand-alone function append
append(h, c);
that is not related to the class List.
You even did nit declare in main an object of the type List.
Pay attention to that the class ListNode has the data member of the type int.
int value;
However you are trying to save in this data member objects of the type char that are element of a vector declared like vector<char> c.
And it is totally unclear why the default constructor of the class ListNode initializes the data member value with the character 'b'.
ListNode:: ListNode() {
value = 'b';
next = NULL;
}
So the code in whole does not make sense.
It seems that you mean that the data member value of the class ListNode had the type char instead of int.
char value;
In this case the function append of the class List can be declared and defined the following way
void List:: append( const std::vector<char> &v )
{
ListNode **current = &head;
while ( *current ) current = &( *current )->next;
for ( const auto &item : v )
{
*current = new ListNode( item, nullptr );
current = &( *current )->next;
}
}
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.
I'm currently taking a jab at Project Euler #9 and am encountering segmentation faults. These segfaults only occur with every 3rd-4th time I run the program. Could someone explain why this might be the case and more importantly, why it doesn't segfault (or work) every time instead?
I've pinpointed the segfault to the beginning of the 2nd while loop but still can't determine the root cause.
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main(){
int square, sum, answer = -1;
int start = 1;
LinkedList tripletChoices;
while (square<=1000){
//create new node
node * factor = new node;
factor->root = start;
square = start*start;
factor->square = square;
//insert into list
if (square<=1000) tripletChoices.insertNode(factor);
start++;
}
node * a_factor = tripletChoices.head;
/** segfaults just after this ***********************/
cout<<"before segfault" << endl;
while(a_factor->next!=NULL){
cout<<"after segfault" << endl;
node * b_factor = a_factor->next;
while(b_factor->next!=NULL){
sum = a_factor->square + b_factor->square;
cout<<"A: " << a_factor->square << " B: " << b_factor->square<< " sum:" << sum <<endl;
node * c_factor = tripletChoices.head;
while(c_factor->next!=NULL){
if (sum == c_factor->square){
if ((a_factor->root + b_factor->root + c_factor->root)==1000){
answer = a_factor->root * b_factor->root * c_factor->root;
break;
}
}
c_factor = c_factor->next;
}
b_factor = b_factor->next;
}
a_factor = a_factor->next;
}
cout<<"Answer: " << answer << endl;
}
the rest of my code (if relevant):
LinkedList.h
#ifndef LinkedList_h
#define LinkedList_h
struct node{
int root;
int square;
node *next;
};
class LinkedList{
public:
node * head;
int listLength;
//default constructor creates head node
LinkedList();
//setter method
bool insertNode(node * newNode);
//destructor de-allocates memory used by the list
~LinkedList();
};
#endif
LinkedList.cpp
#include "LinkedList.h"
#include <iostream>
//Default Constructor - initilizes list with head node
LinkedList::LinkedList(){
head = NULL;
listLength = 0;
}
// setter method for inserting a new node
// inserts new node at the head of the list
bool LinkedList::insertNode(node * newNode){
newNode->next = head;
head = newNode;
listLength++;
return true;
}
//Destructor de-allocates memory used by list
LinkedList::~LinkedList(){
node * p = head;
node * q = head;
while(q){
p = q;
q = p->next;
if (q) delete p;
}
}
Undefined behavior because of accessing uninitialized local variable
You are accessing uninitialized variable square before entering while loop, so it may or may not enter the while loop. So tripletChoices.head may or may not be non-null as you can't be sure if there would have happened any insertion or not!
Thus, dereferencing the null valued a_factor in while(a_factor->next!=NULL) would cause the SegFault.
I'm trying to create a program that reads from a text file and stores the words into a singly linked list. I'm supposed to create my own linked list as opposed to using the STL. I've tried looking up a fair number of tutorials, but I keep getting an error on the variable "head." It says "a value type of Node cannot be used to initialize an entity of type Node"
This is List.cpp:
#include "List.h"
#include "Node.h"
#include <iostream>
using namespace std;
void List::add(string s){
Node* newNode = new Node();
newNode->addString(s);
newNode->setNext(NULL);
Node *temp = head;
if(temp != NULL)
{
while(temp->Next() != NULL)
{
temp = temp->Next();
}
temp->setNext(newNode);
}
else
{
head = newNode;
}
}
void List::print(){
Node *temp = head;
if(temp == NULL)
{
cout<<"EMPTY"<< endl;
return;
}
if(temp->Next() == NULL)
{
cout<<temp->Word();
cout<< "-->";
cout<< "NULL" << endl;
}
else
{ do{
cout<<temp->Word();
cout<<"-->";
temp = temp->Next();
}
while( temp != NULL);
cout << "NULL" << endl;
}
}
void List::read(ifstream& fin){
while(!fin.eof())
{
fin>>sTemp;
add(sTemp);
}
}
This is Node.h
using namespace std;
#include <string>
class Node
{ string val;
Node* next;
public:
Node(void){}
Node(string s)
{
val = s;
next = nullptr;
}
void addString(string aString){ val = aString;};
void setNext(Node* aNext){next = aNext;};
string Word(){return val;};
Node* Next(){return next;};
string sTemp;
};
This is List.h
#include <string>
#include <fstream>
#include "Node.h"
using namespace std;
class List{
Node* head;
public:
List()
{
head = NULL;
}
void print();
void add(string s);
void find(string key);
void read(ifstream& fin);
string sTemp;
}
Under the actual List.cpp, it gives me an error when I say Node *temp = head; with the aforementioned error. Any reason why and how can I fix this?
Part of the problem here is that in List.cpp you've included Node.h twice.
directly includes List.h which itself includes Node.h
directly includes Node.h
I'm surprised that the compiler didn't warn you about this. It seems instead that it chose to redefine Node hence you end up with two Node values which aren't compatible. You need to add include guards to your header files to prevent double includes
List.h
#if !LIST_H
#define LIST_H
...
#endif
Node.h
#if !NODE_H
#define NODE_H
...
#endif
Also note that it's generally speaking considered bad practice to have using statements in header files. Instead use namespace qualified names in headers and put the using statements into the .cpp files.
I'm trying to implement a linked list in C++, but every time I compile, I get an error that says 'Node* Node::nextPtr' is private. If I change nextPtr to have public protection, then I don't get the error and my list is fine. Can someone tell me why this is and how to fix it? My list and node classes are as follows:
//list.h
#include <string>
#include "node.h"
using namespace std;
class List
{
public:
List();
bool isEmpty();
void insertAtFront(string Word);
void displayList();
private:
Node * firstPtr;
Node * lastPtr;
};
//node.h
#ifndef NODE_H
#define NODE_H
#include <string>
using namespace std;
class Node
{
public:
Node(string arg);
string getData();
private:
string data;
Node * nextPtr;
};
//node.cpp
#include <iostream>
#include <string>
#include "node.h"
using namespace std;
Node::Node(string arg)
:nextPtr(0)
{
cout << "Node constructor is called" << endl;
data = arg;
}
string Node::getData()
{
return data;
}
//list.cpp
#include <iostream>
#include "list.h"
#include "node.h"
using namespace std;
List::List()
:firstPtr(0), lastPtr(0)
{
}
bool List::isEmpty()
{
if(firstPtr == lastPtr)
return true;
else
return false;
}
void List::displayList()
{
Node * currPtr = firstPtr;
do
{
if(currPtr->nextPtr == lastPtr) // Error here
cout << endl << currPtr->getData() << endl;
cout << endl << currPtr->getData() << endl;
currPtr = currPtr->nextPtr; //Error here
}
while(currPtr != lastPtr);
}
void List::insertAtFront(string Word)
{
Node * newPtr = new Node(Word);
if(this->isEmpty() == true)
{
firstPtr = newPtr;
cout << "Adding first element...." << endl;
}
else if(this->isEmpty() == false)
{
newPtr->nextPtr = firstPtr; //Error here
firstPtr = newPtr;
cout << "Adding another element...." << endl;
}
}
You didn't show the definitions of your member functions inside the List class, but I bet it is due to those member functions try to access nextPtr from the Node class. You can,
make nextPtr public from Node
add public accessor functions to Node to access it
declare List as a friend from Node, friend class List;
Because somewhere in your code, you access Node * nextPtr by non member functions of class Node. You can create a getter for nextPrt to avoid that.