Brian
Brian

Reputation: 187

c linked list print backwards

I am trying to make a doubly linked list that loops around, so the last link is connected to the first one. However, I cannot figure out what I am doing wrong with the backlink, as I can print my list forwards but not backwards. Any tip/help would be much appreciated.

This is my structure definition:

struct  NODE {
    union {
        int  nodeCounter;
        void  *dataitem;
    } item;

    struct NODE *link;
    struct NODE *backlink;
};

//function to create a list
struct NODE *InitList() {
    struct NODE *temp = (struct NODE*)malloc(sizeof NODE);

    temp->item.nodeCounter = 0;
    temp->link = NULL;
    temp->backlink = NULL;

    return temp;
}

This is my insert function:

void  Add2List(struct NODE *start, struct NODE *NewNode) {
    struct NODE *current = start;

    while (current->link != NULL && current->link != start) {
        current = current->link;
    }
    current->link = NewNode;

    NewNode->link = start;
    NewNode->backlink = current;
    start->backlink = NewNode;

    start->item.nodeCounter++;
}

and this is my print backwards function:

void PrintBackwards(struct NODE *start) {
    struct NODE * current = start;

    while(current->backlink != start) {
        DisplayNode((struct inventory*)current->item.dataitem);
        current = current->backlink; //go one node back
    }
}

Upvotes: 0

Views: 231

Answers (2)

merlin2011
merlin2011

Reputation: 75565

The rest of your functions look reasonable but there are least two mistakes in your PrintBackwards function.

  1. If you had intended to print it starting at the end, you should be starting at start->backlink, not at start.

  2. You should not be checking for NULL in the while loop because your list is circular, so there should not be NULL.

The code below fixes those two mistakes, but I am not sure if there are others.

void PrintBackwards(struct NODE *start)
{

    if(start == NULL || start->backlink == NULL)
        return;
    struct NODE * current = start->backlink;

    while(current->backlink != start)
    {
        DisplayNode((struct inventory*)current->item.dataitem);
        current = current->backlink; //go one node back
    }

}

Upvotes: 3

Jiminion
Jiminion

Reputation: 5168

Maybe....

while(current->backlink != start)
{
    DisplayNode((struct inventory*)current->item.dataitem);  //dangerous
    current = current->backlink; //go one node back
}

Upvotes: 1

Related Questions