TrustTyler
TrustTyler

Reputation: 55

Can't traverse from tail to head in doubly link list

I've wrote the code for doubly link list in C, and it is traversing fine from head to tail but on traversing from tail (end) to head it gets stuck in an infinite loop and print only the data of the last node only and I can't figure out what's wrong.

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *prev;
    struct node *next;
};
typedef struct node list;

list *head, *current, *newn, *end;

int main() {
    int x, y;
    current = (list*)malloc(sizeof(list));
    printf("enter data:");
    scanf("%d", &current->data);

    current->next = NULL;
    current->prev = NULL;
    head = current;
    printf("do you want to enter more:");
    scanf("%d", &x);
    while (x == 1) {
        current->next = (list*)malloc(sizeof(list));
        printf("enter data:");
        scanf("%d", &current->next->data);
        current->next->prev = current->next;
        current->next->next = NULL;
        current = current->next;
        end = current;
        printf("do yo want to enter more:");
        scanf("%d", &x);
    }

    newn = head;
    while (newn != NULL) {
        printf("%d:%d:%d->", newn->prev, newn->data, newn->next);
        newn = newn->next;
    }
    while (end->prev != NULL) {
        printf("%d", end->data);
        end = end->prev;
    }
}

Upvotes: 0

Views: 325

Answers (1)

Marian
Marian

Reputation: 7482

Putting together answers from comments, here is the fixed code:

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *prev;
    struct node *next;
};
typedef struct node list;
list *head, *current, *newn, *end;

void exitWithFail() {
   printf("Error: exiting.\n");
   exit(1);
}

int main()
{
    int x,y,r;
    current = (list*)malloc(sizeof(list));
    printf("enter data:");
    r = scanf("%d",&current->data);
    if (r != 1) exitWithFail();
    current->next = NULL;
    current->prev = NULL;
    head = end = current;
    printf("do you want to enter more:");
    r = scanf("%d",&x);
    if (r != 1) exitWithFail();
    while(x == 1)
    {
        current->next = (list*)malloc(sizeof(list));
        printf("enter data:");
        r = scanf("%d",&current->next->data);
        if (r != 1) exitWithFail();
        current->next->prev = current; // problem No.1
        current->next->next = NULL;
        current = current->next;
        end = current;
        printf("do yo want to enter more:");
        r = scanf("%d",&x);
        if (r != 1) exitWithFail();    
    }
    newn = head;

    while(newn != NULL)
    {
        printf("%d ",newn->data);
        newn = newn->next;
    }
    printf("\n");
    while(end != NULL)     // Problem No. 2
    {
        printf("%d ",end->data);
        end = end->prev;
    }
    printf("\n");
}

Upvotes: 2

Related Questions