我试图理解我的教授所做的“排队”功能,但我没有得到一些步骤。
struct queue_node {
int item;
struct queue_node* next;
};
typedef struct queue_node* queue;
int enqueue (queue* tail, int i) {
queue n;
queue *iter;
n = (queue)malloc(sizeof(struct queue_node));
if (!n) return 1;
n->item = i;
n->next = NULL;
for (iter=tail; *iter != NULL; iter = &((*iter)->next)
;
*iter = n;
return 0;
}
首先,“typedef struct queue_node*queue;”让我很困惑,所以我试图用这种方式重新解释代码(如果我错了,请更正代码)
struct queue_node {
int item;
struct queue_node* next;
};
typedef struct queue_node queue;
int enqueue (queue **tail, int i) {
queue *n;
queue **iter;
n = (queue)malloc(sizeof(struct queue_node));
if (!n) return 1; --->what does that mean?
n->item = i;
n->next = NULL;
for (iter=tail; **iter != NULL; iter = &((*iter)->next)--->last part of the for is unclear to me... can i rewrite it as "iter = **((iter)->next)"?
;
*iter = n; -->this is the part i don't really get...
return 0;
}
所以在读我教授的解答之前,我试着自己做一个“排队”函数
typedef struct node{
int value;
struct node *next;
}node;
void enqueue(node *head,int data){
if(head->next != NULL){
enqueue(head->next,data);
}
node *new=NULL;
new=malloc(sizeof(node));
new->value=data;
new->next=NULL;
head->next=new;
}
这样好吗?还是我不能用?提前感谢大家的帮助
最佳答案
typedef struct queue_node* queue;
定义了一个新类型,以便您可以编写
queue* myqueue = (queue*)malloc(sizeof(struct queue_node));
而不是
struct queue_node** myqueue = (struct queue_node**)malloc(sizeof(struct queue_node));
正如注释中指出的,这是指向指针类型的指针。
线路
if (!n) return 1;
测试指针
n
是否有效(即不NULL
),如果比较失败,则返回1作为错误代码。现在是密码
for (iter=tail; **iter != NULL; iter = &((*iter)->next)
{
*iter = n; /* -->this is the part i don't really get... */
return 0;
}
在列表上迭代,直到遇到一个
NULL
指针。行
*iter = n;
取消引用当前迭代器(在本例中是指向当前node
的指针,并将n
分配给它。因此,这实际上是搜索队列的末尾,并将新元素赋给末尾。**((iter)->next)
与
&((*iter)->next)
语句对指向
(*iter)->next
的指针的iter
取消引用,因此您只有指向struct queue_node
的实际指针。然后从queue
中获取next
字段。queue
为您提供指向&
引用的元素的指针(它是地址运算符),而您的代码将为您提供next
引用的实际对象。现在你的代码是:
void enqueue(node *head,int data)
{
if(head->next != NULL) /* what happens if head is NULL ?*/
{
enqueue(head->next,data);
}
node *new=NULL;
new=malloc(sizeof(node));
new->value=data;
new->next=NULL;
head->next=new;
}
除了一开始的评论,我看不出有什么问题。但我没有实际测试代码是否运行;)
我希望这能让事情更清楚。:)如果我的解释有任何含糊不清之处,请发表评论,不要简单地投反对票,我知道我不是最有经验的
->next
程序员。关于c - 链表中的入队功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39317868/