循环双向链表删除节点时输出无限内存地址

问题描述 投票:0回答:1

我正在尝试实现一个函数,以在 C 中从循环双向链表的末尾删除节点。但是,当我运行代码时,它会进入无限循环并产生连续的内存地址流作为输出。我怀疑我的 deleteFromEnd() 函数可能有问题。有人可以检查我的代码并帮助我找出问题吗?

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

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

void printList(node* head_ref) { // printing all the nodes
    if(head_ref == NULL) { // If there is no any node in the list
        printf("There are not nodes to print. Add nodes first!\n");
        return ;
    }
    node* tail = head_ref;
    do {
        printf("%d ", tail->data);
        tail = tail->next;
    } while(tail != head_ref);
    
    printf("\n");
}
void insertAtBeg(node** head_ref, int data) { // Insertion at the beginning
    node* newNode = (node*)malloc(sizeof(node));
    newNode->data = data;
    
    if(*head_ref == NULL) { // If there is no any node in the list, link to itself
        newNode->next = newNode;
        newNode->prev = newNode;
        *head_ref = newNode;
        return ;
    }
    node* tail = (*head_ref)->prev;
    
    tail->next = newNode;
    newNode->prev = tail;
    newNode->next = *head_ref;
    *head_ref = newNode;
}

void deleteFromEnd(node** head_ref) { // Deletion from the end
    if(*head_ref == NULL) { // If there is no any node in the list
        printf("There are not nodes to print. Add nodes first!\n");
        return ;
    }

    node* tail = (*head_ref)->prev; // Last node of the list
    node* temp = (*head_ref)->prev; // The node we want to delete
    
    if (*head_ref == tail) { // If there is only one node in the list
        *head_ref = NULL;
        tail = NULL;
    }
    else {
        tail->prev->next = *head_ref;
        (*head_ref)->prev = tail->prev;
    }
    free(temp);
}
int main() {
    node* head = NULL;
    
    // Insertion at the beginning
    insertAtBeg(&head, 1);
    insertAtBeg(&head, 2);
    insertAtBeg(&head, 3);
    insertAtBeg(&head, 4);
    insertAtBeg(&head, 5);
    printList(head); // print all nodes
    
    // Deletion from the end
    
    deleteFromEnd(&head);
    printList(head);
    deleteFromEnd(&head);
    printList(head);
    deleteFromEnd(&head);
    printList(head); // print all nodes
    
    return 0;
}
c pointers data-structures linked-list doubly-linked-list
1个回答
2
投票

至少有这些问题:

缺少更新

insertAtBeg()
中,前一个头节点的
.prev
没有更新。
线索:2 个
.prev
和 2 个
.next
成员需要更新。 OP 的代码完成了这 4 项中的 3 项。

malloc()
失败

更好地检测分配失败。

void insertAtBeg(node** head_ref, int data) {
    node* newNode = (node*)malloc(sizeof(node));
    if (newNode == NULL) {
      TBD_code();
    }
    newNode->data = data;
© www.soinside.com 2019 - 2024. All rights reserved.