gpt4 book ai didi

c - 如何在 C 中为 FIFO 队列上的元素提供标识?

转载 作者:行者123 更新时间:2023-11-30 17:03:35 25 4
gpt4 key购买 nike

我在 C 上有这个队列代码。它可能代表一个 FIFO,但我不知道如何为每个新的不同条目插入“密码”,例如标识符。有人知道吗?

这是我的代码:

#define true 1
#define false 0

#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
#include<process.h>

struct queue_point
{
int element;
struct queue_point* n;
};

struct queue_point *f_ptr = NULL;

int is_que(void);
void add_ele(int);
int remove_ele(void);
void show_ele();

int main(void)
{
int ele,choice,j;

printf("1 To insert an element");
printf("\n2 To remove an element");
printf("\n3 To display all the elements");
printf("\n4 Exit\n");
while(1)
{
printf("\nEnter your choice: ");
scanf("%d", &choice);

switch(choice)
{
case 1:
{
printf("\nElement to be inserted: ");
scanf("%d",&ele);
add_ele(ele);
break;
}

case 2:
{
if(!is_que())
{
j=remove_ele();
printf("\n%d is removed from the queue",j);
printf("\n");
}
else
{
printf("\nQueue is Empty.\n");
}
break;
}

case 3:
show_ele();
break;

case 4:
exit(1);
break;

default:
printf("\nInvalid choice.\n");
break;
}

}

}

/* Function to check if the queue is empty*/
int is_que(void)
{
if(f_ptr==NULL)
return true;
return false;
}

/* Function to add an element to the queue*/
void add_ele(int element)
{
/*dynamically allocate the memory*/
struct queue_point *queue = (struct queue_point*)malloc(sizeof(struct queue_point));

queue->element = element;
queue->n = NULL;
if(f_ptr==NULL)
{
f_ptr = queue;
}
else
{
struct queue_point* ptr;
ptr = f_ptr;
for(ptr=f_ptr ;ptr->n!=NULL; ptr=ptr->n);
ptr->n = queue;
}
}

/* Function to remove an element from the queue*/
int remove_ele()
{
struct queue_point* queue=NULL;
if(is_que()==false)
{
int j = f_ptr->element;
queue=f_ptr;
f_ptr = f_ptr->n;

/*If you have allocated a memory block with the functions malloc(), calloc()
or realloc() then you need to free the previously allocated memory.*/

free (queue);
return j;
}
else
{
printf("\nQueue is empty.\n");
return -9999;
}
}

/* Function to display the queue*/
void show_ele()
{
struct queue_point *ptr=NULL;
ptr=f_ptr;
if(is_que())
{
printf("\nQUEUE is Empty.\n");
return;
}
else
{
printf("\nElements present in Queue are: ");
while(ptr!=NULL)
{
printf("%d\t",ptr->element);
ptr=ptr->n;
}
printf("\n");
}
}

最佳答案

您可以像这样修改结构:

struct queue_point
{
int element;
int identifier;
struct queue_point* n;
};

如果您更喜欢使用字符串作为标识符,则可以编写char identifer[SIZE_OF_YOUR_CHOICE]

关于c - 如何在 C 中为 FIFO 队列上的元素提供标识?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com