Remove a data from a node - c++

#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
class MysticalBag
{
private:
int useCount;
int content;
string itemName;
public:
MysticalBag *next_ptr;
void setAttributes()
{
//Called for showing the items without any placement of item
useCount = 1;
content = 5;
itemName = "Healing Potion";
}
int takeUseCount()
{
return useCount;
}
int takeContent()
{
return content;
}
string takeItemName()
{
return itemName;
}
void setAttributes(int userCount, int content, string itemName)
{
this->useCount = useCount;
this->content = content;
this->itemName = itemName;
}
void itemAdder()
{
cout << "Enter use count (1-3) " <<endl;
cin >> useCount;
cout << "Enter content (1.0 - 100.0) " <<endl;
cin >> content;
cout << "Enter item name as text" << endl;
cin >> itemName;
cout<< itemName <<" is added in the bag."<< endl;
}
void showBag()
{
cout << "Showing bag contents" << endl << endl;
cout << itemName << endl;
cout << "U - "<< useCount <<", C - "<< content << endl;
}
};
int main()
{
char choice1,choice2;
choice1 = 0;
MysticalBag *head, *tail, *navigator;
navigator = new MysticalBag();
navigator->setAttributes();
head = navigator;
tail = navigator;
tail->next_ptr = NULL;
while(choice1 !='x')
{
cout << "What do you want to do with the bag?" << endl;
cout << "(a)dd item" << endl;
cout << "(r)emove item" << endl;
cout << "(s)how items" <<endl;
cout << "e(x)it" <<endl;
cin >> choice1;
if(choice1 == 'a')
{
navigator = new MysticalBag();
if(head==NULL)
{
head=navigator;
tail=navigator;
tail->next_ptr=NULL;
}
navigator->itemAdder();
tail->next_ptr = navigator;
tail = navigator;
tail->next_ptr = NULL;
}
else if(choice1 == 'r')
{
navigator = head;
tail = head;
while(navigator->next_ptr != NULL)
{
navigator = navigator->next_ptr;
tail = navigator;
}
cout << "Do you want to remove "<< navigator->takeItemName() <<" from your bag? (y/n)"<< endl;
cin >> choice2;
if(choice2 == 'y')
{
navigator = head;
if(navigator == head)
//I am stuck at this point!
navigator = NULL;
cout << "Item removed." << endl;
tail = head;
while(tail->next_ptr != NULL)
{
tail = tail->next_ptr;
}
}
else
{
cout<< "No item removed" <<endl;
}
navigator = head;
if(navigator == head && navigator == tail)
{
navigator = NULL;
head = NULL;
tail = NULL;
}
else
{
navigator = tail;
navigator = NULL;
tail = NULL;
tail = head;
while(tail->next_ptr != NULL)
{
tail = tail->next_ptr;
}
}
}
else if(choice1 != 'x')
{
navigator = head;
while(navigator != NULL)
{
navigator->showBag();
navigator = navigator->next_ptr;
}
}
}
getch();
}
My objective is removing data from a node.
the user can put in data in the node, which is the Navigator.
What I am thinking of is to point navigator to head and Making head recalling the setAttributes(). Which will show the "Healing potion". But, if the user adds to items. How would I remove just one item at a time?

Can you only remove the last item added to the bag, or can any item be removed? The more general case is asking about deletions from a linked list.
To remove an node (item) from a linked list(bag), you need to know the parent of the item you wish to remove. The parent of a node is the node who's next_ptr is the node. So in the loop, you need to track the parent of navigator:
while(navigator->next_ptr != NULL)
{
/* a sample list */
/* "parent" --> "navigator" --> "navigator->next_ptr" */
parent = navigator; /* now we know who points to navigator */
navigator = navigator->next_ptr;
tail = navigator;
}
Once we know the parent of navigator, all that needs to be done to remove navigator is:
parent->next_ptr = navigator->next_ptr;
/* now the list looks like */
/* "parent" --> "navigator->next_ptr" */
And now navigator is removed from the bag.
I think there are still issues with many of your while loops, but fixing them requires knowing more about your intentions.

Is this a list? Why don't you use std::list from inside your custom class?

Well, in short, what you're asking is 'How do a I access a class function if I have a pointer to a class member?' At least that's how I see it.
#include "Items.h" //let me assume you have some sort of struct or class for items in your bag
class Bag : public player { //player would give access to attributes like HP/MP/Who Owns the bag, etc..
protected:
vector<Item*> Contents;
int MaxItems;
public:
Bag();
Store(Item* It);
Remove(Item* It);
UseItem(Item* It);
};
Bag::Store(Item* It) {
if(Contents.size() >= MaxItems) return;
for( int i = 0; i < Contents.size(); i++ ) {
if(It == Contents[i] ) {
return;
}
}
Contents.push_back(It);
}
Bag::Remove(Item* It) {
for(int i = 0; i < Contents.size(); i++) {
if( It == Contents[i] ) {
Contents.erase(Contents.begin() + i);
break;
}
}
Bag::UseItem(Item* It) {
if(!(It->Usable())) { return };
It->Use();
}
class Item {
protected:
int ItemType; //suggest you use some enum for this
public:
Item();
virtual bool Usable();
virtual void Use();
};
Item::Item() { };
bool Item::Usable() {
//Purely Virtual
}
void Item::Use() {
//Same
}
class Potion : public Item {
protected:
int PotionType; //Again, I'd enum this
public:
Potion();
virtual bool Useable();
virtual void Use();
}
Potion::Potion() { ItemType = POTION; }
bool Potion::Useable() { return true; }
void Potion::Use() { //Purely Virtual }
class HealPotion : public Potion {
protected:
int Strength; //who knows, # of hp to heal
public:
HealPotion();
virtual void Use();
};
HealPotion::HealPotion() { PotionType = Heal; Strength = 45; }
void HealPotion::Use() { Owner->ChangeHits(Strength);
this->RemoveItem(this); } //Now you might also want to destroy the item to free up memory

Related

Mistakes in Summary report code using linked lists

I am currently doing a C++ project for my uni assignments. I came across a bit difficulty to code this using linked list.
#include <iostream>
#include<stdlib.h>
#include <string.h>
#include <iomanip>
#include <conio.h>
#define MAX 100
using namespace std;
class User
{
public:
struct user_details
{
string data1;
user_details *next1;
};
struct user_date
{
string data2;
user_date *next2;
};
struct event
{
string data4;
event *next_event;
};
void push_user (string name, string date,string eventss)
{
user_details *newName;
user_date *newDate;
event *newEvent;
cout <<"\n\nList of Events services offered.\n1.Wedding\n2.Birthday\n3.Funeral\n4.Celebration event\n5.Open House"<<endl;
cin.sync();
cout<<"\nEnter name: ";
getline(cin, name);
cin.sync();
cout <<"Enter date: ";
getline(cin, date);
cin.sync();
cout<<"Write the events(e.g. Course.style-Wedding or Buffet.style-Wedding): "<< endl;
getline(cin, eventss);
if(top1 == NULL|| top2 == NULL||top_event==NULL) //checking for empty stack
{
top1 = new user_details;
top1-> data1= name;
top1->next1= NULL;
top2 = new user_date;
top2->data2=date;
top2->next2=NULL;
top_event = new event;
top_event->data4= eventss;
top_event->next_event= NULL;
}
else
{
newName= new user_details;
newName->data1 = name;
newName->next1 = top1;
top1 = newName;
newDate= new user_date;
newDate->data2 = date;
newDate->next2 =top2;
top2= newDate;
newEvent= new event;
newEvent->data4 = eventss;
newEvent->next_event= top_event;
top_event = newEvent;
cout<<"Added new user to stack."<<endl;
}
}
void pop_user (string name, string date, string eventss)
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top2 == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top_event == NULL)
{
cout <<"!!!Stack underflow"<<endl;
}
else
{
name = top1->data1;
current1 = top1;
top1 = top1->next1;
delete current1;
date = top2->data2;
current2=top2;
top2 = top2->next2;
delete current2;
eventss = top_event->data4;
current23 = top_event;
top_event = top_event->next_event;
delete current23;
cout << "Name: "<< name<<endl;
cout << "Date: " << date<<endl;
cout<<"Event" << eventss << " is removed " << endl;
}
}
void display_user ()
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL)
{
cout<<"\nEmpty list" << endl;
// return;
}
else
{
current1 = top1;
current2 =top2;
current23=top_event;
while(current1 != NULL || current2 !=NULL||current23 != NULL)
{
cout<<"\nName: "<< current1->data1<<endl;
current1 = current1->next1;
cout <<"Date: "<<current2->data2<<endl;
current2 = current2->next2;
cout<<"Event: " << current23->data4<<endl;
current23 = current23->next_event;
}
}
}
void deleteStack_user()
{
user_details *current1;
user_date *current2;
event *current23;
if(top1 == NULL || top2 ==NULL||top_event==NULL)
return;
else
{
current1 = top1;
current2 = top2;
current23=top_event;
while(current1 != NULL || current2 != NULL||current23 != NULL)
{
top1 = top1->next1;
delete current1;
current1 = top1;
top2 = top2->next2;
delete current2;
current2 = top2;
top_event = top_event->next_event;
delete current23;
current23 = top_event;
}
}
}
void search(string user_name) //linear search
{
user_details *current1;
cout <<"Please enter the name you want to search: "<<endl;
cin.sync();
getline(cin,user_name);
if(top1==NULL)
{
cout<<"not found";
}
else
{
current1 = top1;
while(user_name==current1->data1||current1 != NULL)
{
cout<<"\nName: "<< current1->data1<<endl;
current1 = current1->next1;
cout <<"Found."<<endl;
}
}
}
user_details *top1=NULL;
user_date *top2=NULL;
event *top_event;
};
class reeves
{
public:
struct node
{
string data;
node *next;
};
void push(string menu)
{
node *newMenu;
cout<<"Enter the menu: ";
cin.sync();
getline(cin, menu);
if(top == NULL) //checking for empty stack
{
top = new node;
top->data= menu;
top->next= NULL;
cout<<"\nCreated new menu."<<endl;
}
else
{
newMenu= new node;
newMenu->data = menu;
newMenu->next = top;
top = newMenu;
cout<<"Added new menu to stack."<<endl;
}
}
void pop(string menu)
{
node *current;
if(top == NULL)
{
cout<<"!!!Stack underflow" << endl;
}
else
{
menu = top->data;
current = top;
top = top->next;
delete current;
cout<<"Menu " << menu << " is removed " << endl;
}
}
void display()
{
node *current;
if(top == NULL)
{
cout<<"\nEmpty menu" << endl;
// return;
}
else
{
current = top;
while(current != NULL)
{
cout<<current->data<<endl;
current = current->next;
}
}
}
void deleteStack()
{
node *current;
if(top == NULL)
return;
else
{
current = top;
while(current != NULL)
{
top = top->next;
delete current;
current = top;
}
}
}
node *top=NULL;
};
class summary_report_price
{
public:
//double wedding_menu=22.00; //per person
//double birthday_menu=17.00;
//double funeral_menu=16.00;
//double celebrationEvent_menu=30.00;
//double openHouse_menu=25.00;
summary_report (){}
~summary_report(){}
struct quantity
{
int Num;
quantity *next_quantity;
};
struct total_quantity
{
int total;
total_quantity *next_total;
};
void enter_quantity(int Quantity, int totalRevenue)
{ int choose;
int price;
quantity *newQuantity;
total_quantity *newTotal;
cout << "\n\nWhich event did you previously choose?\n1.Wedding\n2.Birthday\n3.Funeral\n4.Celebration Event\n5.Open House.\n"<<endl;
cin>>choose;
switch(choose)
{
case 1:
cout <<"Wedding..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*22;
break;
case 2:
cout <<"Birthday..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*17;
break;
case 3:
cout <<"Funeral..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin>>Quantity;
totalRevenue=Quantity*16;
break;
case 4:
cout <<"Celebration Event..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*30;
break;
case 5:
cout <<"Open House..."<<endl;
cout <<"Enter how many people that will be attending: "<<endl;
cin >>Quantity;
totalRevenue=Quantity*25;
break;
case 6:
exit(1);
break;
default:
cout<<"You can only press 1-6 only."<<endl;
}
if(top_quantity == NULL||top_total==NULL) //checking for empty stack
{
top_quantity = new quantity;
top_quantity->Num= Quantity;
top_quantity->next_quantity= NULL;
top_total= new total_quantity; //calc total
top_total->total=totalRevenue;
top_total->next_total=NULL;
}
else
{
newQuantity= new quantity;
newQuantity->Num= Quantity;
newQuantity->next_quantity= top_quantity;
top_quantity= newQuantity;
newTotal= new total_quantity;
newTotal->total=totalRevenue;
newTotal->next_total=top_total;
top_total= newTotal;
}
}
void pop_price(int Quantity, int totalRevenue)
{
quantity *current36;
total_quantity *current71;
if(top_quantity== NULL)
{
cout<<"!!!Stack underflow" << endl;
}
if(top_total== NULL)
{
cout<<"!!!Stack underflow" << endl;
}
else
{
Quantity = top_quantity->Num;
current36 = top_quantity;
top_quantity= top_quantity->next_quantity;
delete current36;
totalRevenue = top_total->total;
current71=top_total;
top_total = top_total->next_total;
delete current71;
cout << "Quantity: "<< Quantity <<endl;
cout << "Total: RM" << totalRevenue<< " is removed " << endl;
}
}
void display_totalRevenue()
{
quantity *current36;
total_quantity *current71;
if(top_quantity == NULL || top_total==NULL)
{
cout<<"\nEmpty revenue" << endl;
// return;
}
else
{
current36 = top_quantity;
current71=top_total;
while(current36 != NULL || current71 !=NULL)
{
cout<<"\nQuantity: "<<current36->Num<<endl;
current36 = current36->next_quantity;
cout<<"Total: RM"<<current71->total<<endl;
current71=current71->next_total;
}
}
}
quantity *top_quantity;
total_quantity *top_total;
};
So here's the problem I'm facing, supposedly I tried to access these structs from different classes of linked lists and make it print out into a summary report. That was the plan, as soon as I entered data it only shows me the list is empty.
Below is the function I'm having trouble with...is there another way to do this? Sorry for the mistakes. I am just a beginner to programming for C++
void QuantityReady(User::user_details *current1, User::user_date *current2, User::event *current23, summary_report_price::quantity *current36, summary_report_price::total_quantity *current71,int count)
{
//quantity
summary_report_price::quantity *temp3;
temp3=current36;
//totalRevenue
summary_report_price::total_quantity *temp5;
temp5=current71;
//struct user_details
User::user_details *temp;
temp=current1;
//struct user_date
User::user_date *temp1;
temp1=current2;
//struct event
User::event *temp2;
temp2=current23;
int i,j;
int HoldNum, tempCount= count, sizeM[tempCount], countM[tempCount];
int RevenueM[tempCount], HoldRevenue;
string NameM[tempCount], HoldName;
string DateM[tempCount], HoldDate;
string EventM[tempCount], HoldEvent;
string events1="Course style-Wedding ";
string events2="Course style-Birthday ";
string events3="Course style-Funeral ";
string events4="Course style-Celebration Event ";
string events5="Course style-Open House ";
string events6="Buffet style-Wedding ";
string events7="Buffet style-Birthday ";
string events8="Buffet style-Funeral ";
string events9="Buffet style-Celebration Event ";
string events10="Buffet style-Open House ";
system("cls");
if(current1==NULL||current2==NULL||current23==NULL||current36==NULL||current71==NULL)
{
cout<<"The list is empty..."<< endl;
cout<<"Press any key to continue ..."<<endl;
getch();
}
else
{ User::user_details *next1;
User::user_date *next2;
User::event *next_event;
summary_report::quantity *next_quantity;
summary_report::total_quantity *next_total;
i=0;
while (i<tempCount)
{
RevenueM[i]=temp5->total;
temp5=temp5->next_total;
sizeM[i]=temp3->Num; //quantity
temp3=temp3->next_quantity;
;
NameM[i]=temp->data1;//struct user details
temp=temp->next1;
DateM[i]=temp1->data2; // user date
temp1=temp1->next2;
EventM[i]=temp2->data4; //event
temp2=temp2->next_event;
i=i+1;
}
j=0;
for(i=0;i<tempCount; i++)
{
for(j=i+1; j<tempCount; j++)
{
if(sizeM[i]<sizeM[j]&&NameM[i]<NameM[j]&&DateM[i]<DateM[j]&&EventM[i]<EventM[j]&&RevenueM[i]<RevenueM[j]) //bubble sorting algorithm
{
HoldRevenue=RevenueM[i];
RevenueM[i]=RevenueM[j];
RevenueM[j]=HoldRevenue;
HoldNum=sizeM[i];
HoldName=NameM[i];
sizeM[i]=sizeM[j];
NameM[i]=NameM[j];
sizeM[j]=HoldNum;
NameM[j]=HoldName;
//date
HoldDate=DateM[i];
DateM[i]=DateM[j];
DateM[j]=HoldDate;
//event
HoldEvent=EventM[i];
EventM[i]=EventM[j];
EventM[j]=HoldEvent;
}
}
}
for(i=0;i<tempCount;i++)
{
countM[i]=0;
}
cout<<"\t\t\t\tReeves Cartering Summary Report"<<endl;
for(i=0;i<tempCount;i++)
{ temp1=current2;
temp2=current23;
temp3=current36;
temp5=current71;
temp=current1;
while (temp!=NULL||temp1!=NULL||temp2!=NULL||temp3!=NULL||temp5 !=NULL)
{
if(temp->data1==NameM[i]||temp1->data2==DateM[i]||temp2->data4==EventM[i]||temp3->Num==sizeM[i]||temp5->total==RevenueM[i])
{
if(temp2->data4.compare(events1)==0)
{
cout<<temp->data1<< " "<<temp2->data4<<temp1->data2 <<temp3->Num<<" "<<temp5->total; //quantity
}
if(temp2->data4==events2)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events3)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events4)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events5)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events6)
{
cout<<temp->data1<< " "<<temp2->data4<<temp1->data2 <<temp3->Num<<" "<<temp5->total; //quantity
}
if(temp2->data4==events7)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events8)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events9)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
if(temp2->data4==events10)
{
cout<<temp->data1<<" "<<temp2->data4<<temp1->data2<<temp3->Num<<" "<<temp5->total;
}
countM[i]=1;
}
temp3=temp3->next_quantity;
temp5=temp5->next_total;
temp1=temp1->next2;
temp2=temp2->next_event;
temp=temp->next1;
}
}
cout<<"Press any key to continue...";
getch();
}
}
```
Your mistake is on the following line:
if(current1==NULL||current2==NULL||current23==NULL||current36==NULL||current71==NULL)
It means if any of those are null than it will print out The list is empty, you never changed current23 71 or 36 from their default value, why do you think they will not be null??
summary_report::quantity *temp3;
temp3=current36;
//totalRevenue
summary_report::total_quantity *temp5;
temp5=current71;
//struct user_details
User::user_details *temp;
temp=current1;
//struct user_date
User::user_date *temp1;
temp1=current2;
//struct event
User::event *temp2;
temp2=current23;
At this point your current 1 through 10 are all null, after you intialize the current 23, 71 etc will null as well...

Cannot figure out constructor errors

I have come across a couple of compiler errors in my code where it is saying. I have been working on this assignment and these seem to be the last two errors that I am comming across and would love some help on why it will not compile, I just want to go to bed :(
main.cpp:103:29: error: in c++98 'actors' must be initialized by constructor, not by '{...}'
list<string> actors = {};
and
main.cpp:138:19: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]
actors = {};
Below is a copy of my two files! Thank you!
#include <iostream>
#include <list>
using namespace std;
class BST
{
// Defines the main components of the node object, as well as refrences the left and right elements
struct node
{
string show;
string year;
string genre;
string URL;
list <string> actors;
node*left;
node*right;
};
node* root;
// Deletes all the nodes of the tree
node* makeEmpty(node* t)
{
if(t == NULL)
{
return NULL;
}
else
{
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
return NULL;
}
// Inserts a node in the tree
node* insert(string x, string year, list<string> actors, node* t)// DO not include Genrem or URL
{
if(t == NULL)
{
t = new node;
t->show = x;
t->year = year;
t->actors = actors;
t->left = t->right = NULL;
}
else if(x < t-> show)
{
t->left = insert(x, year, actors, t->left);
}
else if(x > t-> show)
{
t->right = insert(x, year, actors, t->left);
}
else
{
return t;
}
}
//Finds the minimum most node to the left
node* findMin(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->left == NULL)
{
return t;
}
else
{
return findMin(t->left);
}
}
// Finds the maximum most node to the right
node* findMax(node* t)
{
if(t == NULL)
{
return NULL;
}
else if(t->right == NULL)
{
return t;
}
else
{
return findMax(t->right);
}
}
// Finds a node with the given parameters
node* find(node* t, string x )
{
if(t == NULL)
{
return NULL;
}
else if(x.at(0) < t-> show.at(0))
{
return find(t->left, x);
}
else if(x.at(0) > t->show.at(0))
{
return find(t->right, x);
}
else
{
return t;
}
}
// Prints out the shows inorder
void inorder(node* t)
{
if(t == NULL)
{
// Do nothing
}
else
{
inorder(t->left);
cout << "- " << t->show << endl;
inorder(t->right);
}
}
// Prints the shows of a given actor
void findShow(node* t, string person, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
while(!t->actors.empty())
{
if(t->actors.front() == person)
{
list.push_front(t->show);
break;
}
t->actors.pop_front();
}
findShow(t->left, person, list);
findShow(t->right, person, list);
}
}
// Prints the shows within a given year
void findYear(node* t, string year, list<string> &list)
{
if(t == NULL)
{
// Do nothing
}
else
{
if(t->year == year)
{
list.push_front(t->show);
}
findYear(t->left, year, list);
findYear(t->right, year, list);
}
}
public:
BST()
{
root = NULL;
}
~BST()
{
root = makeEmpty(root);
}
// Public calls to modify the tree
// Inserts a node with the given parametersremove
void insert(string x, string year, list<string> actors)
{
root = insert(x, year, actors, root);
}
// Removes a node with the given key
// void remove(string x, node* t)
// {
// root = remove(x, root);
// }
// Displays all shows within the tree
void displayShows()
{
inorder(root);
}
// Displays all the actors with a given show
void displayActors(string show)
{
root = find(root, show);
if(root != NULL) // THIS LINE
{
list<string> temp = root-> actors;
while(!temp.empty())
{
cout << "- " << temp.front() << endl;
temp.pop_front();
}
}
else
{
cout << "root is NULL." << endl;
}
}
// Displays the shows of a given actor
void displayActorsShows(string actor)
{
list<string> show;
findShow(root, actor, show);
while(!show.empty())
{
cout << "- " << show.front() << endl;
show.pop_front();
}
}
// Searches the tree with the given node
void search(string x)
{
root = find(root, x);
}
};// end of class
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include "source.cpp"
using namespace std;
void scanFile(string fileName);
void printActors(string movie);
void printShows(string actor);
const int MAX_LINE = 128;
int movies = 0;
BST tree;
int main(){
// Scan file
scanFile("tvDB.txt");
// Print all the show titles
cout << "All show titles:" << endl;
tree.displayShows();
cout << endl; // Whitespace
// Print actors /w given show
cout << "Actors from 'The Saint'" << endl;
printActors("The Saint");
// Print show /w given actor
printShows("Tim Conway");
// Print from decade
return 0;
}
// Trims the line removing all excess whitespace before and after a sentence
string isolateLine(string line)
{
int index = 0, start = 0, end = 0;
//Get the start of the line
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
start = i;
break;
}
}
// Get the end of the line
for(int x = line.length(); x >= 0; x--)
{
if(line[x] != ' ' && line[x] != '\t')
{
end = x;
break;
}
}
// Trim line
line = line.substr(start, end);
return line;
}
// A boolean that returns if the tree is blank, useful for skipping a line and continuing to search for a movie
bool blankLine(string line){
for(int i = 0; i < line.length(); i++)
{
if(line[i] != ' ' && line[i] != '\t')
{
return false;
}
}
return true;
}
// Prints all the shows an actor has starred in
void printShows(string actor){
cout << "Shows with [" << actor << "]:" << endl;
tree.displayActorsShows(actor);
cout << endl; // whitespace
}
// Prints all the actors in a particular movie
void printActors(string show)
{
cout << " Actors for [" << show << "]" << endl;
tree.displayActors(show);
cout << endl;
}
// Scans the fild and categorizes every line of data into the proper categories of the show
void scanFile(string fileName)
{
ifstream inFile;
inFile.open("tvDB.txt");
list <string> actors = {};
string line = "";
string title = "";
string year = "";
while(getline(inFile, line))
{
line = isolateLine(line);
if(!blankLine(line))
{
// Get movie title
if(line.find('(') != std::string::npos)
{
title = line.substr(0, line.find('(')-1);
}
// Get movie year
if (line.find('(') != std::string::npos) {
year = line.substr(line.find('(') + 1, line.find(')'));
year = year.substr(0, year.find(')'));
}
// Add to actors list
actors.push_back(line);
}
else
{
if(!actors.empty()) // pops the title
{
actors.pop_front();
}
}
tree.insert(title, year, actors);
actors = {};
movies++;
}
}
You have two options in this case:
Using C++11 is acceptable, in that case you can leave the code as-is but add -std=c++11 to your compilation flags (e.g. in your Makefile).
Replace usage of the initializer list:
list <string> actors = {}; -> list <string> actors; (documentation)
actors = {}; -> actors.clear(); (documentation)

Why is it that, when I try to shift all of the strings into my custom made Queue template and try to print, it only prints the last in the queue?

Truth be told, this is an assignment that I'm trying to complete. The basic thing that we have to do is create a Stack and Queue without STL and then create Stack and Queue with STL. I pretty much finished up creating my custom Stack, and it works perfectly. However, with Queue, whenever I try to shift strings into it and print it out, the console will only print out the string that was the last to be shifted. On top of that, whenever I try to unshift the last thing entered into the Queue with the code that I have, I end up getting a read access violation, that of which I am completely stumped on resolving.
If you don't mind, can you look through my code and help me understand what I did that is causing this error and the last entry in my Queue to be the only one printed out? Thanks in advance.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Node {
//create a node struct
string data;
Node *next;
};
class Stack {
public:
Stack();
~Stack();
void push(string a);
string pop();
string toString();
bool isEmpty();
private:
Node * top;
};
class Queue {
public:
Queue();
~Queue();
void shift(string a);
string unshift();
string toString();
bool isEmpty();
private:
Node * top;
Node * bottom;
int count;
};
Stack::Stack() {
//initializes stack to be empty
top = NULL;
}
Queue::Queue() {
//initializes stack to be empty
top = NULL;
}
Stack::~Stack() {
//deconstructor to delete all of the dynamic variable
if (top == NULL) {
cout << "Nothing to clean up" << endl;
}
else {
cout << "Should be deleting..." << endl;
}
}
Queue::~Queue() {
//deconstructor to delete all of the dynamic variable
if (bottom == NULL) {
cout << "Nothing to clean up" << endl;
}
else {
cout << "Should be deleting..." << endl;
}
}
void Stack::push(string a) {
//Need a new node to store d in
Node *temp = new Node;
temp->data = a;
temp->next = top;//point the new node's next to the old top of the stack
top = temp;//point top to the new top of the stack
}
void Queue::shift(string a) {
//Need a new node to store d in
Node *temp = new Node;
temp->data = a;
temp->next = NULL;//point the new node's next to the old top of the stack
if (isEmpty()) {
top = temp;
}
else {
top->next = temp;
count++;
}
top = temp;//point top to the new top of the stack
}
string Stack::pop() {
if (!isEmpty()) {
string value = top->data;
Node *oldtop = top;
top = oldtop->next;
delete oldtop;
return value;
}
else {
cout << "You can't pop from an empty stack!" << endl;
exit(1);
}
}
string Queue::unshift() {
if (isEmpty()) {
cout << "You can't unshift an empty Queue!" << endl;
exit(1);
}
else{
Node *oldbot = top;
if (top == bottom) {
top = NULL;
bottom = NULL;
}
else {
string value = top->data;
}
delete oldbot;
count--;
}
}
string Stack::toString() {
string result = "top ->";
if (isEmpty()) {
result = result + "NULL";
return result;
}
else {
Node *current = top;
while (current != NULL) {
result = result + current->data + "->";
current = current->next;
}
result = result + "(END)";
return result;
}
}
string Queue::toString() {
string result = "top ->";
if (isEmpty()) {
result = result + "NULL";
return result;
}
else {
Node *current =top;
while (current != NULL) {
result = result + current->data + "->";
current = current->next;
}
result = result + "(END)";
return result;
}
}
bool Stack::isEmpty() {
return(top == NULL);
}
bool Queue::isEmpty() {
return(top == NULL);
}
int main()
{
Stack *s = new Stack();
cout << "Output when empty: " << endl << s->toString() << endl;
s->push("Cheeseburger");
s->push("Pizza");
s->push("Large coffee");
s->pop();
cout << "Output when not empty: " << endl << s->toString() << endl;
delete s;
cin.get();
Queue *b = new Queue();
cout << "Output when empty: " << endl << b->toString() << endl;
b->shift("Cheeseburger");
b->shift("Pizza");
b->shift("Large coffee");
cout << "Output when not empty: " << endl << b->toString() << endl;
b->unshift();
delete b;
cin.get();
}
You have to comment below statement in Queue::shift method -
top = temp;

The order of the user input names and weights are all over the place and not ascending. Why is the doubly linked list not linking properly?

The program is supposed to accept user input names and weights on alternating separate lines and while those are being input, it should be building the doubly linked list in order of ascending names for one pointer and ascending weights for the other pointer. If input name already ordered they print fine, but the weights are messed up and if I input out of order its a disaster. I have tried writing it all down on paper to get a visual of what the computer would be doing, but I cant figure out why this not working.
user input:
jim
150
tom
212
micheal
174
output:
jim
212
tom
1
micheal
1
#include <iostream>
#include <string>
using namespace std;
//Node class for the linked list
class Node
{
public:
string name = " ";
int weight = 1;
Node *nextName;
Node *nextWeight;
Node();
};
Node::Node()
{
nextName = NULL;
nextWeight = NULL;
}
void namePrint(Node *nHead, int counter1);
void weightPrint(Node *wHead, int counter2);
void lister(string name, int weight, Node *builder, Node *nHead, Node *wHead);
Node namePlace(string name, Node *builder, Node *next, Node *nHead);
void weightPlace(int weight, Node *builder, Node *next, Node *wHead);
int main()
{
Node *builder;
Node *nHead;
Node *wHead;
string name;
int weight;
int counter = 0;
builder = new Node;
nHead = builder;
wHead = builder;
cout << "Please enter names and weights on alternating seperate lines." <<
"\n When you are ready to show the results please enter: \n 'print by name' or 'print by weight'" <<
"\n enter 'end program' to end the program" << endl;
do
{
if (counter > 0)
{
cin.ignore();
}
getline(cin, name);
if (name == "end program")
{
system("PAUSE");
return 0;
}
else if (name == "print by name")
{
namePrint(nHead, counter);
}
else if (name == "print by weight")
{
weightPrint(wHead, counter);
}
else
{
cin >> weight;
if (counter > 0)
{
lister(name, weight, builder, nHead, wHead);
}
else
{
builder->name = name;
builder->weight = weight;
nHead = builder;
wHead = builder;
}
counter++;
}
} while (name != "end program");
system("PAUSE");
return 0;
}
void lister(string name, int weight, Node *builder, Node *nHead, Node *wHead)
{
Node *next = nHead;
namePlace(name, builder, next, nHead);
next = wHead;
weightPlace(weight, builder, next, wHead);
}
Node namePlace(string name, Node *builder, Node *next, Node *nHead)
{
bool spot = false;
while (spot == false)
{
if (name < nHead->name)
{
builder = new Node;
builder->name = name;
builder->nextName = nHead;
nHead->nextName = builder;
spot = true;
return *builder;
}
else if (name < next->name || next->nextName == NULL)
{
builder = new Node;
builder->name = name;
builder->nextName = next->nextName;
next->nextName = builder;
spot = true;
return *builder;
}
else if (name > next->name)
{
next = next->nextName;
//return namePlace(name, builder, next, nHead);
}
}
}
void weightPlace(int weight, Node *builder, Node *next, Node *wHead)
{
bool spot = false;
while (spot == false)
{
if (weight < wHead->weight)
{
builder->weight = weight;
builder->nextWeight = wHead;
wHead = builder;
spot = true;
}
else if (weight < next->weight || next->nextWeight == NULL)
{
builder->weight = weight;
builder->nextWeight = next->nextWeight;
next->nextWeight = builder;
spot = true;
}
else if (weight > next->weight)
{
next = next->nextWeight;
//weightPlace(weight, builder, next, wHead);
}
}
}
void namePrint(Node *nHead, int counter1)
{
Node *next = nHead;
for (int i = 0; i < counter1; i++)
{
cout << next->name << endl;
cout << next->weight << endl;
next = next->nextName;
}
}
void weightPrint(Node *wHead, int counter2)
{
Node *next = wHead;
for (int i = 0; i < counter2; i++)
{
cout << next->name << endl;
cout << next->weight << endl;
next = next->nextName;
}
}

Searching for data in a linked list

The first part of my program is to extract specific data from a file and insert it into a linked list. I successfully created that part of the program but I'm having difficulty searching through my linked list and printing data. This is my code so far:
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node *next;
};
Node *world;
void makeList(Node *&world);
void printCountry (Node *&world, string name);
int main ()
{
string name;
makeList(world);
printCountry (world, name);
return 0;
}
void makeList(Node *world)
{
ifstream inFile("population.csv");
if (!inFile.fail())
{
cout << "File has opened successfully." << endl;
}
else
{
cout << "File has failed to open." << endl;
exit(1);
}
double temp, temp1, temp2, temp3, population;
string countryName;
Node *top = new Node;
world = top;
while (!inFile.eof())
{
top -> next = NULL;
inFile >> temp >> temp1 >> temp2 >> temp3 >> population;
getline (inFile, countryName);
top -> ctry.population = population;
top -> ctry.name = countryName;
if (!inFile.eof())
{
top -> next = new Node;
top = top -> next;
}
}
// check if list is created successfully
while (world -> next != NULL)
{
cout << world -> ctry.population << " " << world -> ctry.name << endl;
world = world -> next;
}
}
void printCountry (Node *world, string name)
{
string countryToFind;
cout << "What country do you want to find? " << endl;
cin >> countryToFind;
while (world != NULL)
{
if (world -> ctry.name == countryToFind)
{
cout << "Country has been found: " << world -> ctry.name << " has a population of "
<< world -> ctry.population << endl;
break;
}
else
{
if (world -> next == NULL)
{
cout << "End of file" << endl;
break;
}
world = world -> next;
}
}
}
When I run the printCountry, it just searches through the list and prints End of file. What did I do wrong in the printCountry?
you should really separate
1) data structure (linked list)
2) CSV parser
3) loading the parsed data to the linked list.
Here's an example using C#.
public class LinkedList<T> : IEnumerable<T>
{
private class Node<T>
{
public T Value { get; set; }
public Node<T> Next { get; set; }
}
private Node<T> _startingNode;
public void Add(T item)
{
//define the next node
var nextNode = new Node<T>()
{
Value = item
};
//add the node to the end
Node<T> lastNode = this.GetLastNode();
if (lastNode == null)
{
this._startingNode = nextNode;
}
else
{
lastNode.Next = nextNode;
}
}
public IEnumerator<T> GetEnumerator()
{
Node<T> lastNode = this._startingNode;
while (lastNode != null)
{
yield return lastNode.Value;
if (lastNode.Next == null)
{
yield break;
}
lastNode = lastNode.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
private Node<T> GetLastNode()
{
var lastNode = this._startingNode;
while (lastNode != null)
{
if (lastNode.Next == null)
{
break;
}
lastNode = lastNode.Next;
}
return lastNode;
}
}
public class Program
{
public static void Main()
{
//load the list
var numberList = new LinkedList<int>();
numberList.Add(100);
numberList.Add(200);
numberList.Add(300);
numberList.Add(400);
//do something with it
foreach (var item in numberList)
{
Console.WriteLine("Item {0}", item);
}
}
}