如何创建头节点

Cir*_*nor 1 c linked-list

我想我在newList中弄错了.不能更改Typedef结构实现.这是我学校的实验室作业..在此先感谢:)

#include<stdio.h>

    typedef struct node *nodeptr;
    struct node {
    int item;
    nodeptr next;
};
typedef nodeptr List;


List newList(); 
Run Code Online (Sandbox Code Playgroud)

newList创建一个头并返回一个指向头节点的指针

void display(List list);
void addFront(List list, int item);

List newList(){
    List list;
    list=(nodeptr)malloc(sizeof(List));
    list->next=NULL;
    return list;
} //I think my new list is incorrect..
void display(List list){
    nodeptr ptr=list;
    while(ptr!=NULL){
        printf("%d",ptr->item);
        ptr=ptr->next;
    }
    printf("\n");
}
void addEnd(List list, int item){
    nodeptr temp, ptr;
    temp=(List)malloc(sizeof(nodeptr));
    temp->item=item;
    temp->next=NULL;
    if(list->next==NULL)
        list=temp;
    else{
        ptr=list;
        while(ptr->next!=NULL)
            ptr=ptr->next;
        ptr->next=temp;
    }

}
Run Code Online (Sandbox Code Playgroud)

我似乎无法从列表中添加10 ..

int main(void){
    List list=newList();
    addEnd(list,10);
    display(list);
}
Run Code Online (Sandbox Code Playgroud)

小智 5

根据您的实际需要,有很多方法可以解决这个问题(因为只创建一个节点本身并没有多大意义).但通常您有三个常见选项 - 在堆栈上创建它,在全局内存中创建该节点,或动态分配它.以下是一些例子.

在堆栈上

#include <stdlib.h>

struct node {
    int item;
    struct node *next;
};

int main()
{
    struct node head;
    head.item = 0;
    head.next = NULL;
    /* Do something with the list now. */
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

在全球记忆中

#include <stdlib.h>

struct node {
    int item;
    struct node *next;
};

static struct node head;

int main()
{
    /* Do something with the list now. */
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

动态分配

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

struct node {
    int item;
    struct node *next;
};

int main()
{
    struct node *head;

    head = calloc(1, sizeof(struct node));
    if (head == NULL) {
        perror("calloc");
        return EXIT_FAILURE;
    }
    /* Do something with the list now. */
    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

您可以在任何介绍性C书中阅读上述任何示例.

希望能帮助到你.祝好运!