String wont store in linked list - c++

#include <iostream>
#include <string.h>
using namespace std;
class MovieList {
private:
struct MovieNode {
string title;
struct MovieNode *next;
};
MovieNode *head;
public:
void appendNode(string var);
void displayList();
};
void MovieList::appendNode(string var) {
MovieNode *newNode, *nodePtr;
newNode = new MovieNode;
newNode->title = var;
newNode->next = NULL;
if (!head) {
head = newNode;
}
else {
nodePtr = head;
while (nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
cout << endl << "Input has been successfull!" << endl;
}
void MovieList::displayList() {
MovieNode *nodePtr;
if (head == NULL) {
cout << "The list is empty!" << endl;
}
else {
cout << "The nodes in the List are... " << endl;
nodePtr = head;
while (nodePtr) {
cout << nodePtr->title << endl;
nodePtr = nodePtr->next;
}
}
}
int main() {
MovieList list;
string var;
cout << " << Enter Movie >> " << endl << endl;
cout << "Enter a movie: ";
getline(cin, var);
list.appendNode(var);
list.displayList();
}
My question is why does the string variable won't show in the display void. The code is working at first when I try inputting a string but then it exits the program without displaying what I input. Is something wrong with how I put the string or is it in implementing the string into the node? please help, I'm new in linked list.

One issue is that MovieList.head is not initialized when you create a MovieList object.
Thus when MovieList.append() is called, this line:
if (!head)
causes the behavior of the program to be erratic due to the head pointer being whatever value it is, which you have no idea what the value is. It may be nullptr, thus the program works, but it may be any other values.
The bottom line is that you should initialize your member variables when you create an object. You can either create a default constructor that initialized head, or you can initialize head directly inline at the declaration point:
class MovieList
{
private:
struct MovieNode
{
string title;
struct MovieNode *next;
};
MovieNode *head;
public:
MovieList() : head(nullptr) {} // Using constructor
void appendNode(string var);
void displayList();
};
or:
class MovieList
{
private:
struct MovieNode
{
string title;
struct MovieNode *next;
};
MovieNode *head = nullptr; // Initialized here
public:
void appendNode(string var);
void displayList();
};

Related

How to generate unique ID in linked list?

I am currently learning how to use linked list in class in my free time. Now I only know how to insert, display and delete. I can delete by using int age; but I think it would be better if I'm able to generate a unique ID that is easier for user to remember(user-friendly), for each data in the linked list so that I could delete by its ID.
I want to know if there is a possible way for me to generate a unique ID in the getInput(); function?
If yes, please give me a hint how to do it. Thanks!
struct list
{
list *head, *tail;
list *next;
}
class node
{
private:
std::string name; // Name
int age; // Age in integer
float height; // In meters
public:
node *next; // Pointer to next node
node *head, *tail;
node *start_ptr = NULL; // Start Pointer (root)
node *temp;
node *temp2;
node *pNextValue;
node* prev; // empty header
node* current;
void printList();
void delete_end_node();
void search();
void sort_age();
void deletebyAge();
node()
{
head = NULL;
tail = NULL;
}
void getInput()
{
temp = new node;
cout << "ID: ";
// This is where I want to generate unique ID
cout << "Name: ";
cin >> temp->name;
cout << "Age: ";
cin >> temp->age;
cout << "Height: ";
cin >> temp->height;
cout<<"\n";
temp->next = NULL; // Sets the node to be the last node
if (start_ptr == NULL)
start_ptr = temp;
else
{
temp2 = start_ptr; // We know temp2 is not NULL - list not empty!
while (temp2->next != NULL) // The loop will terminate when temp2
temp2 = temp2->next; // points to the last node in the list
// Move to next link in chain
temp2->next = temp; // Sets the pointer from that last node to point to the node that has just declared
}
} // End of getInput() function
}; //End of class
In C++ the identity of an object is its address. You can use node address as its id, e.g.:
class node
{
private:
std::string name; // Name
int age; // Age in integer
float height; // In meters
friend std::ostream& operator<<(std::ostream& s, node& n) {
return s << "id:" << &n
<< ' ' << "name:" << n.name
<< ' ' << "age:" << n.age
<< ' ' << "height:" << n.height
<< '\n';
}
// the rest of your code...
};
And then print it like:
node n;
std::cout << n;
Alternatively, use a serial counter:
class node
{
private:
std::string name; // Name
int age; // Age in integer
float height; // In meters
unsigned const id;
static unsigned object_counter;
public:
node()
: id(++object_counter)
{}
friend std::ostream& operator<<(std::ostream& s, node& n) {
return s << "id:" << n.id
<< ' ' << "name:" << n.name
<< ' ' << "age:" << n.age
<< ' ' << "height:" << n.height
<< '\n';
}
// the rest of your code...
};
unsigned node::object_counter = 0;

C++ Need help accessing values inside of linked list

class Node {
public:
Node();
void setNext(Node*);
private:
void* item;
Node* next;
};
void Node::setNext(Node* n)
{
next = n;
}
class List {
public:
List();
void addFirst(void*);
void reset();
void* getCurItem();
private:
Node* head;
Node* current;
};
void List::addFirst(void* obj)
{
Node *newNode = new Node(obj);
newNode->setNext(head);
head = newNode;
}
void List::reset()
{
current = head;
}
void* List::getCurItem()
{
return current->getItem();
}
Polynomial::Polynomial(std::ifstream& input){
List *polyCo = new List();
List *polyEx = new List();
bool exit = false;
double coefficient=0;
int exponent=0;
while(!exit && input.good()){
input >> coefficient;
if(coefficient != -9999.99){
input >> exponent;
cout << "Exponent before: " << exponent << endl;
cout << "Coefficient before: " << coefficient << endl;
int *ExPtr = &exponent;
double *CoPtr = &coefficient;
cout << "Exponent: " << *(ExPtr) << endl;
cout << "Coefficient: " << *(CoPtr) << endl;
polyCo->addFirst(ExPtr);
polyEx->addFirst(CoPtr);
cout << polyCo->getCurItem() << endl; //SEG FAULT
}
}
polyEx->reset();
polyCo->reset();
}
I am reading numbers from a file into two separate linked lists. I am getting a segmentation fault when attempting to access the value in either of the linked list.
First, I'm going to outline how I think my addFirst() functions works, because I could just be implementing it incorrectly. When addFirst() is called, a new node is created, and the data being read in is set equal to the member of the new node. The existing node in the list is pushed forward, and the new node created becomes the head. The two nodes are also linked.
There could be something else entirely wrong besides my implementation of the function, but at least it is a good place to start, along with the source of the segmentation fault.

Undefined reference to another class?

I'm using a class within a class and I'm getting errors, I think it's a linking problem. I get "undefined reference to 'Node::setlink()', 'Node::getlink()', and etc. It's all the node functions I used in linked_list.cpp that are the problem.
For example, linked_list.cpp:(.text+0x9de): undefined reference to
`Node::getlink()'
Linked_list.cpp
#include "linked_list.hpp"
#include "node.hpp"
#include <iomanip>
#include <iostream>
using namespace std;
//default constructor
Linked_list::Linked_list(void)
{
head = new Node();
tail = new Node();
head->setlink(NULL);
tail->setlink(NULL);
cnt = 0;
}
//constructor
Linked_list::Linked_list(data x)
{
head = new Node();
tail = new Node();
Node *newnode = new Node(x);
head->setlink(newnode);
newnode->setlink(tail);
cnt++;
}
//class function
void Linked_list::insert_node(data x)
{
Node *newNode = new Node(x);
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
newNode->setlink(tail);
head->setlink(newNode);
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while(curr->getlink() != NULL || newNode->getupc() <= curr->getupc())
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
prev->setlink(newNode);
newNode->setlink(curr);
}
cnt++;
}
//Class function
void Linked_list::delete_node(int u)
{
char choice;
data temp;
Node *newNode = new Node();
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
delete newNode;
delete prev;
delete curr;
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while (curr->getlink() != NULL || curr->getupc() != u )
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
prev->setlink(curr->getlink());
cout << "Are you sure you want to delete?\n";
cin >> choice;
if (choice == 'y' || choice == 'Y')
{
delete curr;
cnt--;
}
else
{
choice = 'n';
}
}
}
//Class function
void Linked_list::traverse()
{
data temp;
Node *curr = new Node();
if (head == NULL)
{
delete curr;
cout << "The list is empty!\n";
}
else
{
curr->setlink(head->getlink());
while(curr->getlink() != NULL)
{
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
}
void Linked_list::retrieve_node(int u)
{
data temp;
Node *x;
x = new Node();
if (head == NULL)
{
delete x;
}
else if (head != NULL)
{
x->setlink(head->getlink());
while (x->getlink() != NULL || x->getupc() != u)
{
x->setlink(x->getlink());
}
temp = x->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
void Linked_list::check_empty()
{
if (head != NULL)
{
cout << "The list is empty.\n";
}
else
{
cout << "The list is not empty.\n";
}
}
linked_list.hpp
#include "node.hpp"
#ifndef linked_list_hpp
#define linked_list_hpp
class Linked_list
{
Node *head;
Node *tail;
int cnt;
public:
//default constructor creates empty linked list
Linked_list(void);
//Constructor that creates first node with values
Linked_list(data x);
//Inserts node at correct spot
void insert_node(data x);
//deletes specific node
void delete_node(int u);
//goes through whole list and prints out
void traverse(void);
//returns specific node
void retrieve_node(int u);
//checks if list is empty
void check_empty();
return_number();
};
#endif
node.hpp
#ifndef node_hpp
#define node_hpp
#include "node.hpp"
#include <string>
using namespace std;
struct data
{
int UPC;
string desc;
int quantity;
double cost;
int aisle;
};
class Node
{
data item;
Node *link;
public:
Node(void);
Node(data x);
void setlink(Node *ptr);
Node* getlink();
int getupc();
data get_structure();
bool compare_item(string i);
double processdata();
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
link = NULL;
}
Node::Node(data x)
{
item = x;
}
void Node::setlink(Node *ptr)
{
link = ptr;
}
Node* Node::getlink()
{
return link;
}
int Node::getupc()
{
return item.UPC;
}
data Node::get_structure()
{
return item;
}
bool Node::compare_item(string i)
{
if(i==item.desc)
{
return true;
}
else
{
return false;
}
}
double Node::processdata()
{
return item.cost*item.quantity;
}
main function
#include <iostream>
#include "node.cpp"
#include "linked_list.cpp"
using namespace std;
void fromfile(Linked_list &x);
void tofile(Linked_list &x);
int main(void)
{
Linked_list ll;
int x, y;
data a;
do
{
cout << "1.Add a grocery item\n" ;
cout << "2.Delete an item\n";
cout << "3.Retrieve an item\n";
cout << "4.Traverse the list forwards and print out all of the items\n";
cout << "5. Exit the program.\n";
cin >> x;
switch(x)
{
case 1:
cout << "Enter UPC code\n";
cin >> a.UPC;
cout << "Enter description(name of item)\n";
cin >> a.desc;
cout << "Enter quantity\n";
cin >> a.quantity;
cout << "Enter cost\n";
cin >> a.cost;
cout << "Enter aisle\n";
cin >>a.aisle;
ll.insert_node(a);
case 2:
cout << "Enter UPC of item you'd like to delete.\n";
cin >> y;
ll.delete_node(y);
case 3:
cout << "Enter UPC code.\n";
cin >> y;
ll.retrieve_node(y);
case 4:
ll.traverse();
case 5:
cout << "Bye!\n";
default:
cout << "Wrong choice, try again!\n";
}
}while (x != 5);
return 0;
}
Please help me out, this is due in 2 hours. I think I got it running somehow for a while and after the code performs in main, it just stop creating output after it reaches a linked_list function. Then, I can't enter anything afterwards.
The only thing not compiling is the linked_list.cpp, and I get a winmain error as well.

Delete node in linked list result in program collapse

I was trying to delete a node in a linked list defined as follows:
typedef struct
{
char key[10];
char name[20];
int age;
}Data;
typedef struct Node
{
Data nodeData;
struct Node *nextNode;
}cltype;
And the the delete function is defined as below:
int clDeleteNode(cltype *head, char *key)
{
cltype *node, *htemp = new (cltype);
htemp = head;
node = head;
while (htemp)
{
if (strcmp(htemp->nodeData.key, key))
{
node->nextNode = htemp->nextNode;
delete htemp;
return 1;
}
else
{
node = htemp;
htemp = htemp->nextNode;
}
}
//delete mp
return 0;
}
And the problem is when I tried to invoke the the delete function in this form the program will collapse:
cout << "program demo for deleting node\n" << "input key:" << endl;
fflush(stdin);
cin >> key;
//scanf("%s", key);
//int i =
if (clDeleteNode(head, key))
{
cout << "Delete Successful" << endl;
}
else
{
cout << "Operation Failed" << endl;
}
clAllNode(head);
The screen will display "Delete Successful", but the clAllNode(...) function will not execute.And the clAllNode(...) functions works totally well at other place, so I guess there is something wrong with the delete operation,can someone tell me where I did wrong?
Thank you.

dev-c++ compiler error no matching function

I was working this code previously but have a new issue with it the link to the old one is Bloodshed Dev-C++ compiler errors *Binary Trees.
I have one error that states in function 'int main()' no matching function for call to 'binaryTreeType::insert(int&)' candidates are: void binaryTreeType::insert () [with elemType = int] not really sure what this is. The code is posted below any help is appreciated thanks in advance.
#include <iostream>
using namespace std;
template <class elemType>
struct nodeType
{
int data;
nodeType *lLink;
nodeType *rLink;
};
template <class elemType>
class binaryTreeType //main class
{
public:
binaryTreeType(); //constructor
~binaryTreeType(); //destructor
void swapSubtreeNodes(); //declares swapSubtreeNodes
void swapSubtreeNodes(nodeType<elemType>*);
void insert();
void printTree();
private:
nodeType<elemType>*root; //declares root pointer
nodeType<elemType> *temp; //declares root pointer
};
template <class elemType>
void binaryTreeType<elemType>::swapSubtreeNodes()
{
swapSubtreeNodes(root); //displays new root
}
template <class elemType>
void binaryTreeType<elemType>::swapSubtreeNodes(nodeType<elemType> *p)
{
root = temp;
nodeType<elemType> *root; //pointer for root
nodeType<elemType> *temp; //pointer for temp
if (p == NULL) //checks for empty pointer
{
return;
}
else
{
swapSubtreeNodes(p->lLink); //do the subtrees
swapSubtreeNodes(p->rLink);
temp = p->lLink; //swap the pointers
p->lLink = p->rLink;
p->rLink = temp;
}
root = temp; //root set equal to temp
}
int main()
{
binaryTreeType<int> (tree);
int num;
cout << "This is how we swap'em" << endl;
cout << "Insert number (press enter after each one entered)." << endl;
cout << "Enter -999 to complete" << endl;
binaryTreeType<int> (insert);
cin >> num;
while (num != -999)
{
tree.insert(num);
cin >> num;
}
cout << "The unswapped binary tree looks like this: " << endl;
tree.printTree();
cout << endl;
cout << "The swapped binary tree looks like this: " << endl;
tree.swapSubtreeNodes();
tree.printTree();
cout << endl;
}
The template member function binaryTreeType<elemType>::insert() takes no arguments. The code tries to call it with an argument of type int.
Your insert method declaration doesn't take any parameters.