lovelivecode
lovelivecode

Reputation: 11

Doubly Linked List Giving Mixed Results?

This is code that my teacher gave us (just the addNode function), so tell me why when I run the input.txt with numbers like 1 2 3 4...

In Visual Studio it comes out 1, 2, 3, 4 ..and on repl, it comes out 4, 3, 2, 1.

I will ask my teacher but it's the weekend, so thanks in advance!

#include <iostream>
#include <fstream>

using namespace std;

struct node {

int data;
node *next = NULL;
node *prev = NULL;

};

void addNode(node *&head, node *&tail, int value) {

    node *temp = new node;
    temp->data = value;
    temp->prev = NULL;

    if (!head) {
        temp->next = NULL;
        tail = temp;
    }

    else {
        temp->next = head;
        head->prev = temp;
    }
    head = temp;
}
void traverse(node *head) {
    node *current = head;

    while (current) {
        cout << current->data << endl;
        current = current->next;
    }
}

int main() {
    node *head, *tail;
    head = tail = NULL;
    int value;

    ifstream in("c:\\temp\\input.txt");

    while (!in.eof()) {
        in >> value;
        addNode(head, tail, value);
    }
    traverse(head);
}

Upvotes: 1

Views: 39

Answers (1)

SHG
SHG

Reputation: 2616

Given input 1 2 3 4 the correct output is 4 3 2 1.

Notice that every time you call addNode() it pushes the new node before head:

else {
    temp->next = head;
    head->prev = temp;
}

and then the new node becomes the new head:

head = temp;

==> when you traverse over the list, the elements will be displayed in an opposite order of their insertion.

Upvotes: 1

Related Questions