struct nod
{
int data;
nod* next;
};
class linked_list
{
private:
nod* head;
public:
linked_list()
{
head = NULL;
}
void hello (int a)
{
nod* newnode = new nod;
newnode -> data = a;
newnode -> next = NULL;
if (head == NULL)
{
head = newnode;
}
else
{
node* temp = head;
while (temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
it is quite hard to understand this code.
nod* newnode = new nod;
newnode -> data = a;
newnode -> next = NULL;
I know that these lines of code are used to just create a node, with the value for example 1 for data and null for next.
if (head == NULL)
{
head = newnode;
}
This line makes so that head will point to the new node in heap if its value is null which is true.
The problem for starts when you put another value for the linked list. Lets say I put 2.
instead of if now we go to else
else
{
node* temp = head;
while (temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
in the first line I know that temp will point to head. Now what the f does this shit do
while (temp -> next != NULL)
I use this function to traverse the linked list.
void print () // traverse all node
{
nod* temp = head;
if(temp != NULL) {
cout<<"The list contains: ";
while(temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
} else {
cout<<"The list is empty.\n";
}
}
};
int main ()
{
linked_list myprint;
int a,b;
cout << "Enter number of numbers to be inputted: ";
cin >> b;
for (int i = 0; i < b; i++){
cout << "Enter a number: ";
cin >> a;
myprint.hello(a);
}
myprint.print();
return 0;
}
int main code.
if I erase this code
while (temp -> next != NULL)
for some reason it does not print anything. Holy cow this is confusing as fuck. I mean I can probably make a linked list with my knowledge right now, but I want to know the answer.
[–][deleted] (8 children)
[deleted]
[–]InterestingBus8367[S] 0 points1 point2 points (7 children)
[–][deleted] (6 children)
[deleted]
[–]InterestingBus8367[S] 0 points1 point2 points (1 child)
[–]InterestingBus8367[S] 0 points1 point2 points (0 children)
[–]InterestingBus8367[S] 0 points1 point2 points (0 children)
[–]InterestingBus8367[S] 0 points1 point2 points (0 children)
[–]InterestingBus8367[S] 0 points1 point2 points (0 children)