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...
Related
A Bank manager want to segregate different Currency notes in to 3 different baskets. Initially, all the currencies are in one Basket and the currencies are USD, INR and EUR. Now, you are supposed to write a program that can segregate the currencies to 3 different buckets. While, segregation, make sure to have a track of the overall sum of the currencies in terms of INR for each basket.
Program Requirements:
1.First get the input from the user for the overall Basket. [Even numbers are mapped as USD, Odd numbers are mapped as INR and Prime numbers are mapped as EUR, if there is an intersection, you are free to select any one of them]
2.After receiving the elements of the Basket, try a function to segregate the currencies
3.While adding the currency to its corresponding basket, ensure to calculate the overall sum.
4.Whenever, the bank manager wants to see the basket, you should display all the baskets and its corresponding SUM, MEAN, MEDIAN and MODE.
5.Also, there should be a provision to remove required amount of currency in each basket. [While removal, you need to enter the amount of removal in INR and its corresponding value should be removed from the respective basket]
NOTE: Use the value, USD = 73 INR and EUR = 86.5 INR
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int prime(int n);
struct node
{
int info;
struct node *next;
}*last;
class circular_llist
{
public:
void insert(int value);
void delete_element(int value);
void display_list();
circular_llist()
{
last = NULL;
}
};
int main()
{
int element, choice, ch;
int arr[100], i, n, x;
int sum_usd=0, sum_inr=0, sum_eur=0;
int c_usd=0, c_inr=0, c_eur=0;
int arr_usd[n], arr_inr[n], arr_eur[n];
cout << "Enter the total number of elements" << endl;
cin >> n;
cout << "Enter the elements:" << endl;
for(i=0;i<n;i++) {
cin >> x;
arr[i]=x;
}
circular_llist usd;
circular_llist inr;
circular_llist eur;
for(i=0;i<n;i++) {
if(prime(arr[i])==1) {
eur.insert(arr[i]);
sum_eur+=arr[i];
c_eur++;
}
else if(arr[i]%2==0) {
usd.insert(arr[i]);
sum_usd+=arr[i];
c_usd++;
} else {
inr.insert(arr[i]);
sum_inr+=arr[i];
c_inr++;
}
}
do{
cout << "1.Delete Element" << endl;
cout << "2.Display elements" << endl;
cout << "3.Show mathematical figures" << endl;
cout << "4.Quit" << endl;
cin >> ch;
switch(ch)
{
case 1:
cout << "From which basket do you want to delete?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
usd.delete_element(element);
cout<<endl;
break;
case 2:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
inr.delete_element(element);
cout<<endl;
break;
case 3:
if (last == NULL)
{
cout<<"List is empty, nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
eur.delete_element(element);
cout<<endl;
break;
}
case 2:
cout << "From whick basket do you want to diplay thye elements?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
usd.display_list();
cout << endl;
break;
case 2:
inr.display_list();
cout << endl;
break;
case 3:
eur.display_list();
cout << endl;
break;
}
case 3:
cout << "For which basket do you want tp show the mathematical figures?" << endl;
cout << "1.USD" << endl << "2.INR" << endl << "3.EUR" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "Sum = " << sum_usd << endl;
cout << "Mean = " << endl;
case 2:
cout << "Sum = " << sum_inr << endl;
case 3:
cout << "Sum = " << sum_eur << endl;
}
case 4:
cout << "EXIT" << endl;
break;
default :
cout << "Choose a valid option" << endl;
break;
}
}while(ch!=4);
return 0;
}
/*
* Create Circular Link List
*/
void circular_llist::insert(int value)
{
struct node *temp;
temp = new(struct node);
temp->info = value;
if (last == NULL)
{
last = temp;
temp->next = last;
}
else
{
temp->next = last->next;
last->next = temp;
last = temp;
}
}
/*
* Deletion of element from the list
*/
void circular_llist::delete_element(int value)
{
struct node *temp, *s;
s = last->next;
/* If List has only one element*/
if (last->next == last && last->info == value)
{
temp = last;
last = NULL;
free(temp);
return;
}
if (s->info == value) /*First Element Deletion*/
{
temp = s;
last->next = s->next;
free(temp);
return;
}
while (s->next != last)
{
/*Deletion of Element in between*/
if (s->next->info == value)
{
temp = s->next;
s->next = temp->next;
free(temp);
cout<<"Element "<<value;
cout<<" deleted from the list"<<endl;
return;
}
s = s->next;
}
/*Deletion of last element*/
if (s->next->info == value)
{
temp = s->next;
s->next = last->next;
free(temp);
last = s;
return;
}
cout<<"Element "<<value<<" not found in the list"<<endl;
}
/*
* Display Circular Link List
*/
void circular_llist::display_list()
{
struct node *s;
if (last == NULL)
{
cout<<"List is empty, nothing to display"<<endl;
return;
}
s = last->next;
cout<<"Circular Link List: "<<endl;
while (s != last)
{
cout<<s->info<<"->";
s = s->next;
}
cout<<s->info<<endl;
}
/*
*Check in the element is prime or not
*/
int prime(int n) {
int i;
int a;
for(i=2;i<n;i++){
if(n%i==0) {
a = 0;
break;
}
}
return a;
}
Change this: int arr_usd[n], arr_inr[n], arr_eur[n];
Into this: int arr_usd[20], arr_inr[20], arr_eur[20];
or any other number other than 20. It shows an error as n value hasn't been initialised yet.
Done completely using LinkedList in C
#include <stdio.h>
#include <stdlib.h>
struct Node{
float data;
struct Node* next;
};
struct Node *EUR=NULL;
struct Node *USD=NULL;
struct Node *INR=NULL;
void sort(struct Node **h){
struct Node* node1;
struct Node* node2;
int temp;
for(node1=*h;node1!=NULL;node1=node1->next){
for(node2=node1->next;node2!=NULL;node2=node2->next){
if(node1->data>node2->data){
temp = node1->data;
node1->data = node2->data;
node2->data = temp;
}
}
}
}
void add(float val,struct Node **h){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = val;
temp->next = NULL;
if(*h==NULL){
*h = temp;
return;
}
struct Node *node = *h;
while(node->next!=NULL){
node = node->next;
}
node->next = temp;
}
void delete(struct Node** h, float amt){
struct Node *node = *h;
if(*h!=NULL){
if(node->data==amt){
*h = node->next;
}else{
int flag=0;
while(node->next!=NULL){
if(node->next->data==amt){
node->next = node->next->next;
flag=1;
printf("[*]Amount removed\n");
break;
}
node = node->next;
}
if(!flag){
printf("[*]Amount not in Basket!!!\n");
}
}
}else{
printf("[*]Failed\tZero Balance\n");
}
}
float sum(struct Node** h){
if(*h==NULL)
return 0;
float s=0;
struct Node *node = *h;
while(node!=NULL){
s += node->data;
node = node->next;
}
return s;
}
float mean(struct Node** h){
if(*h==NULL)
return 0;
int l=0;
float m,s=0;
struct Node *node = *h;
while(node!=NULL){
l++;
s += node->data;
node = node->next;
}
m =s/l;
return m;
}
float median(struct Node** h){
if(*h==NULL)
return -1;
float med;
struct Node* f_node = *h;
struct Node* p_node = *h;
struct Node* s_node = *h;
while(f_node!=NULL && f_node->next!=NULL){
f_node = f_node->next->next;
p_node = s_node;
s_node = s_node->next;
}
if(f_node!=NULL){//odd
med = s_node->data;
}else{
med = (p_node->data+s_node->data)/2;
}
return med;
}
int mode(struct Node **h){
if(*h==NULL)
return 0;
int max_value=0;
int count,max_count = 0;
struct Node *node = *h;
while (node!=NULL){
count = 0;
struct Node *node2 = node->next;
while(node2!=NULL){
if(node->data==node2->data)
count++;
node2 = node2->next;
}
if(count>max_count){
max_value = node->data;
max_count = count;
}
node = node->next;
}
if(max_count==0)
return 0;
return max_value;
}
void print(struct Node** h,char *m){
printf("printing %s>>>\n",m);
if(*h==NULL){
printf("[*]No bills\n");
return;
}
struct Node* node = *h;
while(node->next!=NULL){
printf("%.2f->",node->data);
node = node->next;
}
printf("%.2f\n",node->data);
printf("[*]SUM: %.2f\n",sum(h));
printf("[*]MEAN: %.2f\n",mean(h));
printf("[*]MEDIAN: %.2f\n",median(h));
printf("[*]MODE: %d\n",mode(h));
}
int even(int n){
if(n%2==0)
return 1;
return 0;
}
int prime(int n){
for(int i=2;i<=n/2;i++){
if(n%i==0){
return 0;
}
}
return 1;
}
int main(){
int n;
int num;
printf("Enter total no of bills: ");
scanf("%d",&n);
float eur = 86.5f;
float usd = 73.0f;
for(int i=0;i<n;i++){
printf("Enter bill %d: ",i+1);
scanf("%d",&num);
if(prime(num))
add(eur*num,&EUR);
else if(even(num))
add(usd*num,&USD);
else
add((float)num,&INR);
}
sort(&EUR);
sort(&USD);
sort(&INR);
int ch1,ch2,br=0;
float amt;
while(1){
printf("1.Display Baskets\n2.Delete Amount\n3.Quit\nEnter your choice: ");
scanf("%d",&ch1);
switch(ch1){
case 1:
print(&EUR,"EURO");
print(&USD,"USD");
print(&INR,"INR");
break;
case 2:
printf("Enter amount to be deleted: ");
scanf("%f",&amt);
printf("Delete From>>>\n1.EUR\t2.USD\t3.INR");
scanf("%d",&ch2);
switch(ch2){
case 1:
delete(&EUR,amt);
break;
case 2:
delete(&USD,amt);
break;
case 3:
delete(&INR,amt);
break;
default:
printf("[*]Wrong Input\n");
break;
}
break;
default:
br = 1;
break;
}
if(br)
break;
}
}```
I don't know if I'm linking wrong but I'm compiling this on linux and I'm getting a LOT of undefined references for my node functions. I'm writing a binary search tree to searches for telephones for class that is due tonight.
bst.cpp
#include "bst.hpp"
BST::BST(void)
{
count = 0;
root = NULL;
}
void BST::insert(long long x, string y)
{
Node *newnode = new Node(x, y);
Node *temp;
if (count == 0)
{
root = newnode;
count++;
}
else
{
while(temp->getleft() != NULL && temp->getright() != NULL)
{
if(newnode->getnum() < temp->getnum())
{
temp = temp->getleft();
}
else
{
temp = temp->getright();
}
}
if (newnode->getnum() < temp->getnum())
{
temp->setleft(newnode);
}
else
{
temp->setright(newnode);
}
}
}
Node * BST::getroot(void)
{
return root;
}
Node* BST::delete_node(Node *troot, long long key)
{
if (count == 0)
{
return troot;
}
else if(key < troot->getnum())
{
delete_node(troot->getleft(), key);
}
else if (key > troot->getnum())
{
delete_node(troot->getright(), key);
}
else
{
if(troot->getleft() == NULL && troot->getright() == NULL)
{
delete troot;
troot == NULL;
}
else if(troot->getright() == NULL)
{
Node *temp = troot;
troot = troot->getleft();
delete temp;
}
else if(troot->getleft() == NULL)
{
Node *temp = troot;
troot = troot->getright();
delete temp;
}
}
return troot;
}
void BST::preverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
preverse(troot->getleft());
preverse(troot->getright());
}
void BST::postverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
postverse(troot->getleft());
postverse(troot->getright());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
}
void BST::inverse(Node* troot)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
inverse(troot->getleft());
cout << troot->getname() << endl;
cout << troot->getnum() << endl;
inverse(troot->getright());
}
void BST::search(Node* troot, long long key)
{
if(root == NULL)
{
cout << "The tree is empty\n";
}
if(troot == NULL)
{
return;
}
if(key == troot->getnum())
{
cout << troot->getname();
}
search(troot->getleft(), key);
search(troot->getright(), key);
}
bst.hpp
#include "node.hpp"
#ifndef bst_hpp
#define bst_hpp
class BST
{
Node* root;
long long count;
public:
BST(void);
void insert(long long x, string y);
Node* getroot(void);
Node* delete_node(Node* troot, long long key);
void preverse(Node* troot);
void postverse(Node* troot);
void inverse(Node* troot);
void search(Node* troot, long long key);
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
number = 0;
name = "no name";
left = NULL;
right = NULL;
}
Node::Node(long long t, string n)
{
number = t;
name = n;
left = NULL;
right = NULL;
}
Node * Node::getleft(void)
{
return left;
}
Node * Node::getright(void)
{
return right;
}
void Node::setleft(Node * ptr)
{
left = ptr;
}
void Node::setright(Node * ptr)
{
right = ptr;
}
long long Node::getnum(void)
{
return number;
}
string Node::getname(void)
{
return name;
}
node.hpp
#ifndef node_hpp
#define node_hpp
#include <string>
#include <iostream>
using namespace std;
class Node
{
long long number;
string name;
Node *left;
Node *right;
public:
Node(void);
Node(long long t, string n);
Node* getleft(void);
Node* getright(void);
void setleft(Node* ptr);
void setright(Node* ptr);
long long getnum(void);
string getname(void);
};
#endif
main.cpp
#include "bst.hpp"
using namespace std;
int main(void)
{
int choice;
long long numin;
string input;
BST phbook;
do
{
cout << "1. Insert a name and number.\n2. Delete using number.\n3. Traverse pre-order\n4. Traverse post-order\n";
cout << "5. Traverse in-order\n6. Search using number.\n6. Exit program\n";
switch(choice)
{
case 1:
cout << "Enter a name\n";
cin.ignore();
getline(cin, input);
cout << "Enter a number\n";
cin >> numin;
phbook.insert(numin, input);
break;
case 2:
cout << "Enter the phone number you'd like to delete.\n";
cin >> numin;
phbook.delete_node(phbook.getroot(), numin);
break;
case 3:
phbook.preverse(phbook.getroot());
break;
case 4:
phbook.postverse(phbook.getroot());
break;
case 5:
phbook.inverse(phbook.getroot());
break;
case 6:
cout << "Enter a phone number to search.\n";
cin >> numin;
phbook.search(phbook.getroot(),numin);
default:
numin=numin;
}
}while(choice >= 1 && choice <= 6);
return 0;
}
To me, nothing looks wrong in linking the files.
Some examples : undefined reference to Node::getnum()
undefined reference to Node::getname()
Check the order of compiled elements:
g++ node.cpp -o node.o bst.cpp -o bst.o main.cpp -o main.o
Result:
./main.o
1. Insert a name and number.
2. Delete using number.
3. Traverse pre-order
4. Traverse post-order
5. Traverse in-order
6. Search using number.
6. Exit program
I have made a C++ program for a binary tree. But the terminal is not asking the statement for inputting the direction for where the elements are to be placed.
Also when I replace the statement from " node *temp = new node " to "node *temp=NULL" the program stops working .
#include <iostream>
#include <cstring>
using namespace std;
class node {
int data;
node * left;
node * right;
public:
node * level_order(node * first);
node * create_bt(node * first);
void display(node * first);
};
//node *first=NULL;
node * node::create_bt(node * first) {
node * temp = new node;
int ele;
//char dir;
cout << "\n Enter data ";
cin >> ele;
temp->data = ele;
temp->left = NULL;
temp->right = NULL;
if (first == NULL) {
temp = first;
return first;
} else {
char dir[20];
cout << "\n Enter the direction ";
cin >> dir;
node * cur = first;
int j = 0;
while (dir[j] != '\0') {
if (dir[j] == 'l') {
cur = cur->left;
}
if (dir[j] == 'r') {
cur = cur->right;
}
j++;
}
cur = temp;
return first;
}
}
void node::display(node * first) {
if (first == NULL)
return;
cout << "\n " << first->data;
display(first->left);
display(first->right);
}
int main() {
int n;
node s;
node * first = NULL;
cout << "\n No of elements ";
cin >> n;
for (int i = 0; i < n; i++) {
first = s.create_bt(first);
}
s.display(first);
return 0;
}
first=s.create_bt(first); does not changes state, from NULL to 'l' or 'r'. You have to change that.
node*node::create_bt(node *first)
{
node *temp=new node;
int ele;
//char dir;
cout<<"\n Enter data ";
cin>>ele;
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
char dir[20];
cout<<"\n Enter the direction ";
cin>>dir;
if(first==NULL)
{
temp=first;
return first;
}
else
{
node*cur=first;
int j=0;
while(dir[j]!='\0')
{
if(dir[j]=='l')
{
cur=cur->left;
}
if(dir[j]=='r')
{
cur=cur->right;
}
j++;
}
cur=temp;
return first;
}
}
I believe you re looking something like this. This is a basic binary tree, i had to make a basic one in order to understand how it works and how it chooses left and right. I make a class inside a class, in order to have access to my data members (node class, int data, *left , *right) and have them at the same time protected, all-in-one. As you can see "newnode" just creates a node and NULL s the pointers. Thats it. "Find" searches and finds a node with a current key, and returns it when exits. All the rest, i guess, you can understand them, as they are prety much the same with your code. The only thing you have to do is to define, when you want to direct the node you want. REMINDER: You have to find a way to utilize it, so the leafs will not end far-left or far-right.("Enter the direction"). I hope i helped you understand.
#include <iostream>
#include <conio.h>
using namespace std;
class mybTree {
class node {
public:
int data;
node * left;
node *right;
};
node *root;
node *newnode(int num){
node *newnode1;
newnode1 = new (nothrow) node;
newnode1->data = num;
newnode1->left = NULL;
newnode1->right = NULL;
return newnode1;
}
public:
node *find (int key) {
node *current;
current = root;
while (current->data !=key){
if (key<current->data){
current = current->left;
} else {
current = current->right;
}
if (current == NULL){
return NULL;
}
}
return NULL;
}
void display (node *ptr);
void display_tree();
bool insert(int num);
void post_order_delete(node *ptr);
mybTree();
~mybTree();
};
int main(){
char ch = ' ';
int a;
mybTree mybTree1;
while (ch !='0'){
cout << "0->Exit"<<endl<< "1-> add"<<endl<< "2-> find" <<endl<<"3-> Show me the tree\n";
ch = getch();
switch (ch) {
case '0':
break;
case '1':
cout << "number";
cin >> a;
if (!mybTree1.insert(a)){
cout << "Not enough memory" << endl;
}
break;
case '2' :
cout << "Number:" ;
cin >> a;
if (mybTree1.find(a)!=NULL) {
cout << "Found" << endl;
} else {
cout << "Not existed" << endl;
}
break;
case '3':
mybTree1.display_tree();
cout<<endl;
break;
default:
cout << "Wrong Message";
break;
}
}
return 0;
}
void mybTree::display(node *ptr) {
if (ptr == NULL){
return;
}
display(ptr->left);
cout << ptr->data<<endl;
display(ptr->right);
}
void mybTree::display_tree() {
//Displays the Tree
display(root);
}
bool mybTree::insert(int num) {
//It inserts a node. Desides left or right.
node *next,*current,*ptr;
int isleft;
next = current = root;
ptr = newnode(num);
if (ptr == NULL) {
return false;
}
if (root == NULL) {
root = ptr;
return true;
}
while (1){
if (num < current->data){
next = current->left;
isleft = 1;
} else {
next = current->right;
isleft = 0;
}
if (next == NULL){
if (isleft){
current->left = ptr;
} else {
current->right = ptr;
}
return true;
}
current=next;
}
return false;
}
void mybTree::post_order_delete(node *ptr) {
//deletes the node. Usefull for destructor
if (ptr == NULL){
return;
}
post_order_delete(ptr->left);
post_order_delete(ptr->right);
cout << ptr->data;
delete ptr;
}
mybTree::mybTree() {
//Constructor
root = NULL;
}
mybTree::~mybTree() {
//Destructor
post_order_delete(root);
root = NULL;
}
I have made a Student record system in c++ using the concept of linked list. The program will take the student id, name and marks for 3 different exams. Then it will calculate the aggregate percentage based on those exams marks and display the relevant message according to the aggregate percentage. The program is running without any errors.
But I want student id to be unique. For example, if a user inputs a student id which has been already assigned to previous student than it will show a message that "please enter a different id."
How would I do that. Any help will be appreciated.
struct student
{
int id;
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
struct node
{
struct student *data;
struct node *next;
node()
{
data = 0;
next = NULL;
}
};
struct student *readStudent()
{
clearWindow();
struct student *stdnt = new student;
gotoxy(33,8);cout<<"Student ID: ";
while(!(cin >> stdnt->id) || cin.peek() != '\n')
{
char ch;
cin.clear();
cout << "sorry";
while(cin.get(ch) && ch != '\n');
}
cin.ignore();
gotoxy(33,10);cout<<"Student Name: ";
cin.getline(stdnt->name, 50);
gotoxy(33,12);cout<<"Enter Matriculation Marks: ";
cin>>(stdnt->matric_marks);
gotoxy(33,14);cout<<"Enter Intermediate Marks: ";
cin>>(stdnt->inter_marks);
gotoxy(33,16);cout<<"Enter Entry Test Marks: ";
cin>>(stdnt->entryTest_marks);
stdnt->aggr = calculate_aggregiate(stdnt);
gotoxy(33,18);cout<<"Student Aggregate Marks: "<< stdnt->aggr;
if (stdnt->aggr >= 70)
{
gotoxy(33,20);cout<<"Student Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
gotoxy(33,24);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,20);cout<<"Sorry! The Student Doesnt Qualify";
}
return stdnt;
}
struct node *createDatabase(int size)
{
int i = 0;
struct node *head = NULL;
struct node *last = NULL;
for(i = 0; i < size; i++)
{
struct student *stdnt = readStudent();
struct node * current = new node;
current->data = stdnt;
current->next = NULL;
if(last)
last->next = current;
else
head = current;
last = current;
}
return head;
}
struct node *InsertRecord(struct node *head)
{
struct node *record = new node;
struct student *stdnt = readStudent();
record->data=stdnt;
record->next=head;
return record;
}
double calculate_aggregiate(struct student *stud)
{
student *stdnt = stud;
double aggr;
aggr = stdnt->matric_marks * 10/100 + stdnt->inter_marks * 50/100 +
stdnt->entryTest_marks * 40/100;
return aggr;
}
struct node *DeleteRecord(struct node *head)
{
clearWindow();
struct node *curr,*prev, *temp;
int tdata;
if(head==NULL)
{
gotoxy(33,10);cout<<"NO RECORDS TO DELETE......!";
}
else
{
gotoxy(33,10);cout<<"Enter Student ID To Be Deleted: ";
cin>>tdata;
prev=curr=head;
while((curr!=NULL)&&(curr->data->id!=tdata))
{
prev=curr;
curr=curr->next;
}
if(curr==NULL)
{
gotoxy(33,12);cout<<"The Requested ID Is Not Found...!";
}
else if(curr==head)
{
head=head->next;
gotoxy(33,12);cout<<"DATA DELETED....!";
}
else
{
prev->next=curr->next;
if(curr->next==NULL)
{
temp=prev;
}
gotoxy(33,12);cout<<"DATA DELETED....!"<<tdata;
}
delete(curr);
}
return head;
}
void ModifyRecord(struct node *head)
{
clearWindow();
int ch, sid;
struct node *current;
struct student *stdnt;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO MODIFY..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Modify: ";
cin>>sid;
current=head;
while((current!=NULL) && (current->data->id!=sid))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if(current->data->id==sid)
{
gotoxy(33,10);cout<<"What Do You Want To Modify";
gotoxy(33,12);cout<<"1. Student's Name";
gotoxy(33,14);cout<<"2. Student's Matric Marks";
gotoxy(33,16);cout<<"3. Student's Intermediate Marks";
gotoxy(33,18);cout<<"4. Student's Entry Test Marks";
gotoxy(33,20);cout<<"Enter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1 : gotoxy(33,22);cout<<"Enter New Name: ";
cin.getline(current->data->name, 50);break;
case 2 : gotoxy(33,22);cout<<"Enter New Matric Marks: ";
cin>>(current->data->matric_marks);break;
case 3 : gotoxy(33,22);cout<<"Enter New Intermediate Marks: ";
cin>>(current->data->inter_marks);break;
case 4 : gotoxy(33,22);cout<<"Enter New Entry Test Marks: ";
cin>>(current->data->entryTest_marks);break;
current->data->aggr = current->data->matric_marks * 10/100 + current->data- >inter_marks * 50/100 +
current->data->entryTest_marks * 40/100;
}
gotoxy(33,24);cout<<"RECORD MODIFIED....!";
}
}
}
void SearchRecord(struct node *head)
{
clearWindow();
int s_id;
struct node *current;
if (head==NULL)
{
gotoxy(33,8);cout<<"NO RECORD TO SEARCH..!";
}
else
{
gotoxy(33,8);cout<<"Enter Student ID To Be Searched: ";
cin>>s_id;
current=head;
while ((current!=NULL) && (current->data->id!=s_id))
{
current=current->next;
}
if (current==NULL)
{
gotoxy(33,10);cout<<"The Requested ID is Not Found";
}
else if (current->data->id==s_id)
{
gotoxy(33,10);cout<<"Student ID: "<<current->data->id;
gotoxy(33,12);cout<<"Student Name: "<<current->data->name;
gotoxy(33,14);cout<<"Student Matric Marks: "<<current->data->matric_marks;
gotoxy(33,16);cout<<"Student Intermediate Marks: "<<current->data - >inter_marks;
gotoxy(33,18);cout<<"Student Entry Test Marks: "<<current->data- >entryTest_marks;
gotoxy(33,20);cout<<"Student Aggregate Marks: "<<current->data->aggr;
if (current->data->aggr >= 70)
{
gotoxy(33,22);cout<<"Student Registered In Electrical Engg";
}
else if (current->data->aggr >= 60)
{
gotoxy(33,22);cout<<"Student Registered In Mechanical Engg";
}
else if (current->data->aggr >=50)
{
gotoxy(33,22);cout<<"Student Registered In Computer Science";
}
else
{
gotoxy(33,22);cout<<"Sorry! The Student Doesnt Qualify";
}
}
}
}
void print(struct node *head)
{
clearWindow_p();
struct node *current = head;
if (head == NULL)
{
gotoxy(33,8);cout<<"No Student Registered Yet......!";
}
else
{
cout<<"\n\t\t\t\t\tSTUDENTS STATISTICS";
while(current)
{
struct student *stdnt = current->data;
cout<<"\n\t\t\t\t\t-------------------------------- ";
cout<<"\n\t\t\t\t\tStudent ID :"<<stdnt->id;
cout<<"\n\t\t\t\t\tStudent Name :"<<stdnt->name;
cout<<"\n\t\t\t\t\tMatric Marks :"<<stdnt->matric_marks;
cout<<"\n\t\t\t\t\tIntermediate Marks :"<<stdnt->inter_marks;
cout<<"\n\t\t\t\t\tEntry Test Marks: "<<stdnt->entryTest_marks;
cout<<"\n\t\t\t\t\tAggregate: "<<stdnt->aggr;
if (stdnt->aggr >= 70)
{
cout<<"\n\t\t\t\t\tStudent Registered In Electrical Engg";
}
else if (stdnt->aggr >= 60)
{
cout<<"\n\t\t\t\t\tStudent Registered In Mechanical Engg";
}
else if (stdnt->aggr >=50)
{
cout<<"\n\t\t\t\t\tStudent Registered In Computer Science";
}
else
{
cout<<"\n\t\t\t\t\tSorry! The Student Doesnt Qualify";
}
current=current->next;
}
cout<<"\n\t\t\t\t\t--------------------------------";
}
}
int compareStudents(struct student *left, struct student *right)
{
return strcmp(left->name, right->name);
}
struct node *sort(struct node *head)
{
//using bubble sort
int swapped = 0;
do
{
swapped = 0;
struct node *current = head;
struct node *previous = NULL;
while(current && current->next)
{
if(compareStudents(current->data, current->next->data) > 0)
{
//swap here
struct node *next = current->next;
if(previous)
{
previous->next = next;
}
else
{
head = next;
}
current->next = next->next;
previous = next;
previous->next = current;
swapped = 1;
}
else
{
previous = current;
current = current->next;
}
}
} while(swapped);
return head;
}
int main()
{
system("color f0");
window();
SetColor(28);
int total,i,choice;
int x = 2;
struct node *head;
head=NULL;
do
{
menu:
gotoxy(x, 8);cout<<"1.Create a Record File";
gotoxy(x, 10);cout<<"2.Insert Student's Record";
gotoxy(x, 12);cout<<"3.Modify Student's Record";
gotoxy(x, 14);cout<<"4.Delete Student's Record";
gotoxy(x, 16);cout<<"5.Search Student's Record";
gotoxy(x, 18);cout<<"6.Print All Records";
gotoxy(x, 20);cout<<"7.Sort According To Names";
gotoxy(x, 22);cout<<"8.Clear The Screen";
gotoxy(x, 24);cout<<"9.Exit";
gotoxy(x, 26);cout<<"Enter your choice";
cout<<" [ ]\b\b";
cin>>choice;
switch(choice)
{
case 1:
clearWindow();
gotoxy(33, 8);cout<<"How Many Students Do You Want To Register: ";
cin>>total;
head=createDatabase(total);
break;
case 2:
head=InsertRecord(head);
break;
case 3:
ModifyRecord(head);
break;
case 4:
DeleteRecord(head);
break;
case 5:
SearchRecord(head);
break;
case 6:
print(head);
break;
case 7:
sort(head);
print(head);
break;
case 8:
main();
break;
default: gotoxy(33,8);cout<<"INVALID OPTION";
}
}while(choice!=9);
getch();
return 0;
}
Since you are using C++, you should take advantage of the built-in types. If there is only one student with a given ID, use the std::map<> template. For example:
struct student
{
char name[MAX];
string status;
double aggr;
int matric_marks, inter_marks, entryTest_marks;
};
map<int, student> students;
then, to traverse students:
for (auto i = students.begin(); i != students.end(); ++i) {
int studentId = i->first;
student& student = i->second;
student.aggr = ...
}
(auto is C++11, not all compilers enable it by default IIRC. See here.)
If You know the range of student ids , and it is within a feasible range of memory , you can use a UsedId[] array.
If the range is too big too be held , use a Hashmap ,(MAP in c++) .
I would probably implement something called FindRecordByID.
struct student *FindRecordByID(struct node *head, int id) {
for(; head != NULL; head = head->next)
if (head->data->id == id)
return head->data;
return NULL;
}
Then when you do your create_new_student routine, you could use that to verify that the given ID is not already used.
#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