Итак, я пытаюсь написать метод pu sh для стека в C ++, и я не могу заставить его работать. Вот что у меня есть (и, пожалуйста, простите за беспорядок, я пытался исправить это весь день)
#include <iostream>
using namespace std;
struct ItemInStack
{
string data; //where we're keeping the "stuff"
ItemInStack *next; //address to where we're going next
};
class Stack{
private:
ItemInStack *head;
int data;
public:
Stack(){ //constructor
head = NULL;
}
void pushMethod(string newData){
ItemInStack *tmp = new ItemInStack;
tmp->data = newData;
tmp->next = head; //set next to head since the new item is the new head/top of stack
if(head == NULL) //checking if the first set of data
{
head = tmp;
cout<<"BUG FIX: \ndata = "<<tmp->data<<"\nhead = "<<head<<"\nnext = "<<tmp->next<<endl<<endl;
}
else //the rest of the list, aka the majority of the program
{
head->next = tmp;
head = head->next;
cout<<"BUG FIX: \ndata = "<<tmp->data<<"\nhead = "<<head<<"\nnext = "<<tmp->next<<endl<<endl;
}
}
void display()
{
ItemInStack*tmp; //make a tmp to hold stuff
tmp=head;
cout<<"\n~~START DISPLAY~~\n";
//Here's where im tring to bug-fix
cout<<"-First\ntmp->data = "<<tmp->data<<"\nhead = "<<head<<"\ntmp->next = "<<tmp->next<<endl<<endl;
head = tmp->next;
cout<<"-Second\ntmp->data = "<<tmp->data<<"\nhead = "<<head<<"\ntmp->next = "<<tmp->next<<endl<<endl;
head = tmp->next;
cout<<"-Third\ntmp->data = "<<tmp->data<<"\nhead = "<<head<<"\ntmp->next = "<<tmp->next<<endl<<endl;
head = tmp->next;
//end of bug fix attempt
/* while loop for display once bug-fix is complete
while(tmp->next != NULL)
{
cout<<"\ntmp->next = "<<tmp->next<<"\nhead = "<<head<<endl;
cout << tmp->data << endl; //display
tmp = tmp->next; //move next down the chain
}
*/
}
};
int main()
{
Stack a; //creating an instance of the Stack class
a.pushMethod("Old First");
a.pushMethod("New First");
a.pushMethod("Extra New First");
a.display(); //show me the money
return 0;
}
Насколько я могу судить, я получаю следующий адрес, чтобы указать к предыдущему заголовку правильно, потому что в моей команде BUG FIX он показывает следующее для старого вначале 0 (NULL), затем следующий для New First - это тот же адрес, что и в заголовке Old First, а следующий для Extra New First - это тот же адрес, что и у главы New First. Однако, когда я пытаюсь напечатать его в функции отображения, я не могу правильно перемещаться по списку.
Мой учитель сказал, что он думает (но не был уверен), что каким-то образом мой следующий указатель меняется раньше это достигает дисплея. Любой совет, помощь и т. Д. c будет принята с благодарностью !!