簡體   English   中英

按頭和節點制作鏈表

[英]Making of linked list by head and node

這是我用C語言編寫鏈表的代碼。 while循環執行一次后,它給出運行時錯誤。 請幫助我更正我的代碼。 (完全弄錯了錯誤在哪里。)我先創建一個頭節點,然后向其添加子節點。

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

typedef struct node nd;
typedef nd *link;

struct node{
    int data;
    link next;
};

typedef struct {
    int size;
    link head;
}list;

void create(link temp)
{
    link new;
    new=(link)malloc(sizeof(nd));
    printf("enter data: ");
    scanf("%d",new->data);
    temp->next=new;
    temp=temp->next;
}

list createlist()
{
    list sl;
    sl.size=0;
    sl.head=0;
    return sl;
}

int main()
{
    list sl;
    sl=createlist();
    link temp;
    temp=sl.head;
    char c;
    while (1)
    {
        printf("Add node?: ");
        scanf(" %c",&c);
        if (c=='y')
           {
            create(temp);
            sl.size++;
           }
        else
            break;
    }
    return 0;
}

您的createlist()函數返回對本地變量的引用,該引用在返回后超出范圍。 您應該改為返回基於堆的值:

list* createlist() {
    list* sl = (list*)malloc(sizeof(list));
    sl->size=0;
    sl->head=0;
    return sl;
    }

最初,temp指向NULL。 temp = sl.head;

在create(temp)中temp-> next = new;

您正在取消引用NULL,地址為0x0。 執行此操作時出現細分錯誤。

需要更改算法。 調試器立即顯示此問題。

您可以使用指向temp的指針。 如果您沒有將typedef用作指向節點的指針,則閱讀起來會更容易。 我沒有測試過,但是應該很接近:

nd ** create(nd **temp)
{
    nd *new;
    new=(nd *)malloc(sizeof(nd));  /* this cast shouldn't be needed */
    printf("enter data: ");
    scanf("%d",&(new->data));
    new->next = NULL;
    *temp = new;
    return &(new->next);
}
/* ... */

int main()
{
nd **temp;
temp = &(sl.head);
/* ... */
        temp = create(temp);
/* ... */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM