reversed order linked list

hey im working on this problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace 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.

so if input is 1 2 3 -0
output is 1 2 3.

thats my goal, any suggestions?
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


I'm sure you can figure out how to optimize it ;)
Last edited on
closed account (D80DSL3A)
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).
Topic archived. No new replies allowed.