在双重链接列表中不能从尾部到头部遍历

时间:2017-08-19 08:59:09

标签: c data-structures linked-list doubly-linked-list

我已经在C中编写了双链接列表的代码,并且它从头到尾遍历完好,但是从尾部(结束)到头部遍历它会陷入无限循环并且只打印最后一个数据只有节点,我无法弄清楚出了什么问题。

#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;
    }
}

1 个答案:

答案 0 :(得分:2)

汇总评论的答案,这里是固定代码:

#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");
}