Original Post
Hello, I have programmed two very similar programs that should produce the same output but they do the very opposite. The difference between the two, as far as I can tell, is that one has functions inside its structure while the other doesn't. functions in structures: When I call the Print function only the last structure gets printed in the list. functions outside structures: All the structures get printed in the list. My question to you guys is: why are the two programs acting differently? What can I do to fix this?
#include <iostream>
using namespace std;
struct List
{
int x;
struct List *next;
void Create(int length);
void Print();
};
void List::Create(int length)
{
List *temp = this;
for (int i = 0; i < length; i++)
{
if (i == length - 1)
{
x = i;
next = 0;
break;
}
x = i;
next = new List;
temp = next;
}
}
void List::Print()
{
List *temp = this;
while (temp != 0)
{
cout<<x<<endl;
temp = temp->next;
}
}
int main(void)
{
List *list = new List;
list->Create(20);
list->Print();
return 0;
}
#include <iostream>
using namespace std;
struct intStack
{
int x;
struct intStack *next;
};
void CreateList(intStack *list, int length);
void Print(intStack *list);
int main(void)
{
intStack *List = new intStack;
CreateList(List, 20);
Print(List);
return 0;
}
void CreateList(intStack *list, int length)
{
intStack *temp;
for (int i = 0; i < length; i++)
{
if (i == length - 1)
{
list->x = i;
list->next = 0;
break;
}
list->x = i;
temp = new intStack;
list->next = temp;
list = list->next;
}
}
void Print(intStack *list)
{
while (list != 0)
{
cout<<list->x<<endl;
list = list->next;
}
}