简体   繁体   中英

Reverse order while displaying linked list

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;

}

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

That's how your list looks like after each step of inputting data:

  1. 1
  2. 3->1
  3. 5->3->1
  4. 7->5->3->1
  5. 9->7->5->3->1

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM