In: Computer Science
HOW DO I ACCESS THE HEAD OF A LINKED LIST FROM INT MAIN () WHEN IT'S IN ANOTHER CLASS. HERE IS MY CODE FOR MY MAIN AND HEADER FILES.
HEADER FILE:
#ifndef HANOISTACK_H
#define HANOISTACK_H
#include <iostream>
using namespace std;
class HanoiStack { //class
private:
struct Disc{ //linked list for towers
int num;
Disc* next;
};
Disc* head;
public:
HanoiStack(){ //constructor
head = nullptr;
};
//HanoiStack operator+=(const Disc&);
//HanoiStack operator<<(const Disc&);
void push(int); //push function
int pop(); //pop function
void display(int);//prints pegs
};
#endif
MAIN FILE
int main(){
//class objects
HanoiStack peg;
HanoiStack temp1;
HanoiStack temp2;
HanoiStack temp3;
//integer variables
int num, solved, choice, end, removed, count = 0, tower;
//win condition variable
bool won = false;
cout << "Enter the number of disks" << endl;
cin >> num;//enters the number of disks
while (num > 0 && num < 10){ //confirmation
loop
cout << "Error wrong entry try again" << endl;
cout << "Enter the number of disks" << endl;
cin >> num;
}
if (num > 0 && num < 10){
solved = pow(2, num)-1; //minimum number of moves required to
win
}
for (int i = num; i > 0; i--){
peg.push(temp1); //inserts disks onto tower
}
You need to change the visibility of head from private to public to be able to access it outside the class but that would be a violation of Object-Oriented Programming paradigm. You can modify your class as:
#ifndef HANOISTACK_H #define HANOISTACK_H #include <iostream> using namespace std; class HanoiStack { //class private: struct Disc{ //linked list for towers int num; Disc* next; }; public: Disc* head; HanoiStack(){ //constructor head = nullptr; }; //HanoiStack operator+=(const Disc&); //HanoiStack operator<<(const Disc&); void push(int); //push function int pop(); //pop function void display(int);//prints pegs }; #endif
Now, you can access head of the linked list as:
HanoiStack temp1; cout << temp.head->num << endl; // to print num at head of the list
Avoid this design though. Another approach could be, bring your struct Disc definition out of the class and keep head of the list private in the class. Now, make a member function of the class Disc* getHead() which would return the head of the linked list. Do changes as follow:
#ifndef HANOISTACK_H #define HANOISTACK_H #include <iostream> using namespace std; struct Disc{ //linked list for towers int num; Disc* next; }; class HanoiStack { //class private: Disc* head; public: HanoiStack(){ //constructor head = nullptr; }; Disc* getHead() { return head; } //HanoiStack operator+=(const Disc&); //HanoiStack operator<<(const Disc&); void push(int); //push function int pop(); //pop function void display(int);//prints pegs }; #endif
Now, to access the head of the linked list you could do:
HanoiStack temp1; Disc *temp1head = temp1.getHead(); // this will return head of the linked list of temp1 cout << temp1head->num << endl; // to access number at the head
FOR ANY HELP JUST DROP A COMMENT