Reputation: 31
I have this code, I input 5 random elements 1,3,5,7,9 from the beginning and then I want to display my linked list (1,3,5,7,9), but it is in reverse order for some odd reason (9,7,5,3,1). Could you point out the problem?
#include <iostream> using namespace std;
struct node {
int data;
node * next; };
int n;
int main() {
// input.
cout << "please input 5 elements:\n";
node * head = NULL;
for (int i = 0; i < 5; i++) {
cin >> n;
node * curr = new node;
curr -> data = n;
curr -> next = head;
head = curr;
}
// display
while (head) {
cout << head -> data << "\n";
head = head -> next;
}
return 0;
}
Upvotes: 0
Views: 197
Reputation: 103
That's how your list looks like after each step of inputting data:
If you would like to have the list (1, 3, 5, 7, 9), you would need to insert each element at the end of the list, not in the beginning. So, you would need to have a pointer to the end (it was called a tail, I think) to put the elements in the order you want. The code would look like this:
node * head = NULL, * tail = NULL;
for (int i = 0; i < 5; i++) {
cin >> n;
node * curr = new node;
curr -> data = n;
curr -> next = NULL;
if(head == NULL) {
head = tail = curr;
}
else {
tail -> next = curr;
tail = tail -> next;
}
}
It should work this way.
Upvotes: 1
Reputation: 180500
One way to do this is with recursion. Using the call stack to keep track of each node you would keep traversing the list. Once you reach the end then you print and end the function. This will then propagate back up the call stack printing the next element back up to the start.
void print_revers(node* n)
{
if (n)
print_reverse(n->next)
std::cout << n->data << std::endl;
}
This example assumes that the last node in the list that next
points to NULL
or nullptr
Upvotes: 1