所以我有一个程序,使用int作为输入,并将整数插入到双向链接列表中,其中的功能是createQueueenqueuedequeuedisplaypeek和。我有一个destroyQueue和一个main.c文件,但是问题并不在那里,它在queue.h文件中。问题是当我通过以下命令queue.c用管道传输test12.txt文件并打印到output.txt时,出现分段错误。如果我在enqueue 0 0 display文件中仅运行enqueue 0 0,就没有问题,它可以正常工作。我的问题是,当我编写test12.txt时指向temp的任何内容时,我是否都取消引用display?或者这是一个有效的调用,而我的问题出在temp = temp->prev;节点的初始化上?

queue.c文件:

#include "queue.h"

Queue_ptr createQueue() {
    Queue_ptr s = (Queue_ptr)malloc(sizeof(Queue));
    s->front = NULL;
    s->back = NULL;
    return s;
}

void enqueue(Queue_ptr s, element e) {
    DN_ptr n = (DN_ptr)malloc(sizeof(DLLNode));
    n->e = e;
    if (s->front == NULL) {
        n->next = NULL;
        s->front = n;
        s->back = n;
    }else{
        s->back->next = n;
        n->prev = s->back;
        s->back = n;
    }
}

element dequeue(Queue_ptr s) {
    DN_ptr temp = s->front->next;
    element e = s->front->e;
    free(s->front);
    s->front = temp;
    s->front->next = NULL;
    s->front->prev = NULL;
    return e;
}

int isEmpty(Queue_ptr s) {
    if (s->front == NULL)
        return 1;
    else
        return 0;
}

element peek(Queue_ptr s) {
    return s->front->e;
}

void display(Queue_ptr s) {
    DN_ptr temp = s->back;
    while (temp) {
        printf("%d\n", temp->e);
        temp = temp->prev;
    }
}

void destroyQueue(Queue_ptr s) {
    DN_ptr temp = s->front;
    DN_ptr next;
    while (temp) {
        next = temp->next;
        free(temp);
        temp = next;
    }
    free(s);
}


queue.h文件:

#ifndef queue_h
#define queue_h

#include "stdheader.h"

//Structures

//element is content of a node.
typedef int element;

//_DLLnode is 1 link in a doubly linked list.
struct _DLLNode {
    element e;
    struct _DLLNode *next;
    struct _DLLNode *prev;
};

typedef struct _DLLNode DLLNode;
typedef struct _DLLNode *DN_ptr;

//DLL is a series of links tracked by the head and back of the list.
struct _DLL {
    DN_ptr front;
    DN_ptr back;
};

typedef struct _DLL Queue;
typedef struct _DLL *Queue_ptr;

Queue_ptr createQueue();
void enqueue(Queue_ptr, element);
element dequeue(Queue_ptr);
int isEmpty(Queue_ptr);
element peek(Queue_ptr);
void display(Queue_ptr);
void destroyQueue(Queue_ptr);

#endif /* queue_h */

最佳答案

当队列为空时,不要在n->prev中设置enqueue,当队列不为空时,也不要设置n->next

如果dequeue包含2个以上的元素,则会破坏队列,如果只有1个元素,则崩溃。

这是更正的版本:

void enqueue(Queue_ptr s, element e) {
    DN_ptr n = (DN_ptr)malloc(sizeof(DLLNode));
    n->e = e;
    n->next = NULL;
    if (s->front == NULL) {
        n->prev = NULL;
        s->front = n;
        s->back = n;
    } else {
        s->back->next = n;
        n->prev = s->back;
        s->back = n;
    }
}

element dequeue(Queue_ptr s) {
    DN_ptr temp = s->front->next;
    element e = s->front->e;
    free(s->front);
    s->front = temp;
    if (temp) {
        temp->prev = NULL;
    } else {
        s->back = NULL;
    }
    return e;
}

关于c - 双链表显示功能中的段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35387390/

10-10 00:51