C:Enqueue()-插入链表的末尾,返回链表的头 [英] C: Enqueue() - Inserting at the end of a linked list, returning head of list

查看:48
本文介绍了C:Enqueue()-插入链表的末尾,返回链表的头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程很陌生.尝试编写一个函数,该函数接收列表的头+要插入的数据-并传回列表的新头.我在列表的开头添加了很多元素,但是由于某种原因,我无法绕过这个细微的差别.

I'm very new to programming. Trying to write a function that receives the head of a list + the data to be inserted -- and passes back the new head of the list. I've done this a lot with adding an element to the head of a list, but for some reason I can't wrap my head around this slight difference.

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

typedef struct node_{
    int data;
    struct node_ *next;
} Queue;

int main(void){

   Queue* queue = NULL;

   queue = enqueue(queue, 1);

   assert(queue->next == NULL);
   assert(queue->data == 1);

   queue = enqueue(queue, 2);

   assert(queue->data == 1);
   assert(queue->next != NULL);
   assert(queue->next->data == 2);

   free(queue->next);
   free(queue);

   return 0;

}

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

    Queue *new_node, *p;

    new_node = malloc(sizeof(Queue));

    new_node->data = data;
    new_node->next = NULL;

    p = queue;

    while(p->next != NULL){
        p = p->next;
    }

    p->next = new_node;

    return ??????

}

我知道要插入头部,您可以:

I know that to insert to the head, you can:

new_node->data = data; 
new_node->next = queue;
return new_node;

很抱歉,如果我上面写的没有什么意义.我很累,已经经历了很多次迭代.可能缺少明显的东西.

Apologies if what I've written above doesn't make much sense. I'm pretty tired and I've gone through quite a few iterations. Probably missing something obvious.

推荐答案

只需返回队列.您还必须测试输入的 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;
}

这篇关于C:Enqueue()-插入链表的末尾,返回链表的头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆