簡體   English   中英

如何在 C 中創建一個空鏈表?

[英]How do you create an empty linked list in C?

我有一個 C 代碼,我被分配在其中創建一個空列表。 雖然我創建了一個,元素 = 0,但它仍然被程序認為是一個列表,所以它打印 0,而實際上我希望它打印為 NULL。 此外,當我打印列表的長度時,它也顯示為 1,而不是我要查找的 0。

到目前為止,這是我的代碼。

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

    typedef int ElementType;

    struct Node;
    typedef struct Node *PtrToNode;
    typedef PtrToNode List;
    typedef PtrToNode Position;

    List CreateList();
    int IsEmpty(List L);
    int IsLast(List L);
    Position GetNode(List L,int idx);
    void FetalError(const char *msg);
   void PrintList(List L);

    struct Node {
        ElementType Element;
        Position Next;
        Position Previous;
    };

    List CreateList()
    {
        List L;
        L= (List)malloc(sizeof(struct Node));
        if(L==NULL) FetalError("Out of Memory");
        L->Element = 0;
        L->Next = NULL;
        L->Previous = NULL;
        return L;
    }

Position Insert(ElementType X, List L, Position P)
{
    Position Tmp;
    Tmp=(Position)malloc(sizeof(struct Node));
    if(Tmp==NULL) FetalError("Out of Memory");
    Tmp->Element=X;
    Tmp->Next=P->Next;
    P->Next=Tmp;
    return Tmp;
}

    int IsEmpty(List L){
        return(L->Next==NULL);
    }

    int IsLast(List P){
        return(P->Next==NULL);
    }

       void FetalError(const char *msg)
    {
        printf(msg);
        exit(-1);
    }

    PrintList(List L){

        while(L!= NULL){    
            printf("%d <-> ", L->Element);
            L=L->Next;
        }
        printf("\n");
    }

        int getCount(List L) 
{ 
    int count = 0;  // Initialize count 
    struct Node* current = L;  // Initialize current 
    while (current != NULL) 
    { 
        count++; 
        current = current->Next; 
    } 
        printf("%d number of elements", count); 
} 
    Position GetNode(List L, int idx){

        int i = 0; 
        while (L != NULL) 
        { 
            if (i == idx) 
                return(L); 
            i=i+1; 
            L= L->Next; 
        } 
        return;  
     } 

    Position Last(List L)
    { 
    return L;
    } 

    int main(int argc, char *argv[]) 
    {
        int i;
        ElementType X;
        List L;
        Position P, P1 , P2;

        srand(0);

        // creat an empty list
        printf("Creating an empty list\n");
        L = CreateList();
        PrintList(L);
        getCount(L);

        // Insert at the beginning
        printf("**(Inserting 5 random numbers at the beginning\n");
        for( i=0 ; i<5 ; i++ ) {
            Insert(rand(),L,L);
            PrintList(L);
        }
        P = GetNode(L,5);
        printf("The Element of 5th Node is %d\n",P->Element);
        getCount(L);

        return 0;
    }

你用 memory 創建一個 object,所以它不會是 0\null。 如果你想得到 null object 你應該返回 null。

暫無
暫無

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

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