我正在尝试实现循环队列功能。我是C ++编码人员,但发现在C中struct无法具有成员函数,这使我感到惊讶。无论如何,这是我的实现:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int nvalue;
struct node *next;
};
struct CLlist
{
struct node* head;
struct node* tail;
int size;
};
void insert(struct CLlist *l,int num)
{
struct node *n=malloc(sizeof(struct node));
n->nvalue=num;
n->next=NULL;
if((l->head==l->tail)==NULL)
{
l->head=l->tail=n;
}
else if(l->head==l->tail && l->head!=NULL)
{
l->head->next=n;
l->tail=n;
l->tail->next=l->head;
}
else
{
l->tail->next=n;
l->tail=n;
l->tail->next=l->head;
}
l->size++;
}
void print(struct CLlist *l)
{
int idno=1;
printf("printing the linked list with size as %d\n",l->size);
struct node *cptr;
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
{
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
idno++;
}
//this is to print the last node in circular list : the tail node
idno++;
cptr=cptr->next;
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
}
int main()
{
struct CLlist a;
struct CLlist *l;
l=&a;
insert(l,2);
insert(l,5);
insert(l,7);
insert(l,10);
insert(l,12);
print(l);
return 0;
}
我在行中遇到细分错误
printf(“ idno为%d,数字为%d \ n”,idno,cptr-> nvalue);
为什么会发生错误?我想我没有正确地按值传递l ( 按值传递指针)。有人可以帮助我指出我要去哪里哪里吗?
谢谢
您的代码有两个问题,第一个更严重。
您的第一个问题是未将CLlist结构的head
和tail
成员初始化为NULL
,这可以(不确定)阻止任何实际数据存储在您的结构中。可以通过main
在第一个insert
调用之前添加以下两行来解决此问题:
l->head = NULL;
l->tail = NULL;
您的第二个问题是在此行中:
if((l->head==l->tail)==NULL)
看起来这是在l->head
与和l->tail
进行NULL
比较l->head
时l->tail
,实际上是在与进行比较,然后将该布尔结果与进行比较NULL
,这是有效的0
。该行应更改为:
if((l->head == NULL) && (l->tail == NULL))
这将分别测试head
和tail
指针,并且仅在它们均为NULL时才采用该分支。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句