在C中实现一个双向链表 [英] Implement a doubly linked list in C

查看:67
本文介绍了在C中实现一个双向链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当调用 insertAtBeginning 方法时,我都希望在链表的开头插入一个节点.我的代码构建良好,但是我没有得到想要的输出.

I want to insert a node at the beginning of linked list, whenever insertAtBeginning method is called. My code builds well, but i don't get the desired output.

我得到以下输出:

0------>NULL

所需的输出是:

9------>8------>7------>6------>5------>4------>3------>2------>1------>0------>NULL

以下是我的代码:

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

struct dll{
    int data;
    struct dll* previous;
    struct dll* next;
};


struct dll* insertAtBeginning(int a, struct dll* head){

    if(head == NULL){
        head->data = a;
        head->previous = NULL;
        head->next = NULL;
        return head;
    }
    else{
        struct dll *first;
        first = (struct dll*) malloc( sizeof(struct dll));
        first->data = a;
        first->next = head;
        head->previous = first;
        first->previous = NULL;
        head = first;
        free(first);
        return head;
    }
}


void display_from_first(struct dll* head){
    struct dll *temp;
    temp = head;

    printf("\nThe linked list contains: ");
    while(temp != NULL) {
        printf("%d------>",temp->data);
        temp = temp->next;
    }
    printf("NULL\n");
    free(temp);
    }


int main(){
    int i = 0;
    struct dll *head1, *tail1;
    head1 = (struct dll*) malloc( sizeof(struct dll));
    head1->next = NULL;
    head1->previous = NULL;

    for(i=0; i<10; i++){
        insertAtBeginning(i, head1);
    }

    display_from_first(head1);

    return 0;
}

推荐答案

这里主要有两个问题:

  1. free(first):这不是必需的,因为您希望保存刚分配的内存,而不要删除它.

  1. free(first) : This is not required as you wish to save the memory you just allocated, not delete it.

您的 insertAtBeginning()函数返回指向 head 的指针,因此在 main()中,您将在其中调用此函数将其更改为 head1 = insertAtBeginning(i,head1); 这样也可以保存您的头部.

Your insertAtBeginning() function returns a pointer to head, so in main(), where you are calling this function change it to head1=insertAtBeginning(i, head1); This way your head is also saved.

这是经过两次修改的代码:

Here's the code with the two edits :

http://ideone.com/nXwc8z

这篇关于在C中实现一个双向链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆