且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C:Enqueue()-插入链表的末尾,返回链表的头

更新时间:2022-06-16 02:13:43

只需返回队列.您还必须测试输入的 queue 是否为NULL,在这种情况下,您显然无法访问 next 指针来查找结尾,因此在这种情况下,只需返回新节点.

Just return queue. You also have to test if the input queue is NULL, in which case you obviously can't access a next pointer to find the end, so in that case just return the new node.

Queue *enqueue(Queue *queue, int data){

    Queue *new_node, *p;

    new_node = malloc(sizeof(Queue));
    new_node->data = data;
    new_node->next = NULL;

    if (!queue)
        return new_node;

    p = queue;
    while (p->next)
        p = p->next;
    p->next = new_node;

    return queue;
}