#include <iostream>
usingnamespace std;
struct node{
int data;
node* next;
};
int main() {
node *first, *p;
int value;
first = 0;
cin >> value;
while( value != -0){
p = first;
first = new node;
first -> data = value;
first -> next = p;
cin >> value;
}
for ( p = first; p != 0; p = p -> next){
cout << p -> data << " ";
}
return 0;
}
and what im trying to do is that because the output is reversed of the input,
change somehow in the while loop NOT THE FOR LOOP (because thats easy) how to get the output in the order of the input.
Maybe actually have first be the first element and not the last element?
For the while loop: if first is null
assign a new node to first
set first node data to entered value
set first next to null
else if first->next is null
assign a new node to p
set p node data to entered value
set p next to null
set first->next to p
else
assign a new node to p->next
set p to p->next
set p node data to entered value
set p next to null
Yes. Keep a node* last;
When the 1st node is created (when first==0) assign first = last = new node; + other assigns for data and next.
For all subsequent nodes, last->next = new node; last = last->next; etc.
This way you are adding nodes to the end of the list instead of inserting them at the beginning.
Also, how is it easy to reverse the output by modifying the for loop? The list is singly linked. You can only iterate through it in the forward direction (from first to last).