简体   繁体   English

使用函数指针作为参数

[英]Using a function pointer as parameter

I am trying to add a node to the front of a linked list using the following: 我正在尝试使用以下命令将节点添加到链表的前面:

struct Node *addFront(struct List *list, void *data) {

So far I have the following: 到目前为止,我有以下内容:

struct Node *front = (struct Node *) malloc(sizeof(struct Node)){
    if(front == NULL) {
        return NULL;
    }

    front->data = data;

    if(list->head == 0) {
        list->head = front;
        front->next = NULL;
    }
    else {
        list->head = front;
        *front->next =*
    }

    return front;
}

I am confused as to what an added node would point to if it is not the first node to be created... I would like to say something like: front->next = list; 如果添加的节点不是要创建的第一个节点,我会感到困惑……我想说些类似的东西:front-> next = list; But list is of type List so I'm sure I'd get some incompatible assignment error..what is the best way to go about doing this? 但是list是List类型的,所以我确定会遇到一些不兼容的赋值错误..什么是最好的方法?

Node *oldHead = list->head;
list->head = front;
front->next =oldHead;

Store the old head, and assign it to front->next . 存放旧的头部,并将其分配给front->next

Or just 要不就

front->next =list->head;
list->head = front;

Will suffice. 就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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