简体   繁体   中英

How can I delete the front node of my doubly linked list?

I want to delete the front node in delete_first .

Here is the code:

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

typedef int element;

typedef struct DListNode {
    element data;
    struct DListNode *llink;
    struct DListNode *rlink;
} DlistNode;

void init(DListNode *phead) {
    phead->llink = phead;
    phead->rlink = phead;
}

An error occurs in the part below when I debug.

void print_dlist(DListNode *phead) {
    DListNode *p;
    for (p = phead->rlink; p != phead; p = p->rlink) {
        printf("<-| |%d| |->", p->data);
    }
    printf("\n");
}

This is my insert code and I think it is not problem

void dinsert(DListNode *before, element data) {
    DListNode *newnode = (DListNode *)malloc(sizeof(DListNode));
    newnode->data = data;
    newnode->llink = before;
    newnode->rlink = before->rlink;
    before->rlink->llink = newnode;
    before->rlink = newnode;
}

I want to fix some error in that delete_first code but I don't know what is the problem and how to fix it.

void delete_first(DListNode *head) {
    head = head->rlink;
    if (head != NULL) {
        head->llink = NULL;
    }
    free(head);
}

int main() {
    DListNode *head = (DListNode *)malloc(sizeof(DListNode));
    init(head);
    printf("insert\n");
    for (int i = 0; i < 5; i++) {
        dinsert(head, i);
        print_dlist(head);
    }

    printf("\n delete \n");
    delete_first(head);
    print_dlist(head);

    free(head);
    return 0;
}

How can I delete my front node using the head node?

To delete the first node of the doubly linked list, you must free the node pointed to by head->rlink unless head->rlink points to head itself, which is the case if the list is empty:

void delete_first(DListNode *head) {
    DListNode *p = head->rlink;
    if (p != head) {
        p->llink->rlink = p->rlink;
        p->rlink->llink = p->llink;
        free(head);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM