【发布时间】:2021-09-27 14:59:43
【问题描述】:
我忘记在 display() 方法的开头添加一个临时节点,但后来我添加了它,但我仍然面临同样的问题。我无法在我的代码中找到问题。
我在下面添加了完整的代码:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int key;
struct Node* next;
};
struct Queue
{
struct Node *front, *rear;
};
struct Node* newNode(int k)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->key = k;
temp->next = NULL;
return temp;
}
struct Queue* createQueue()
{
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}
void enQueue(struct Queue* q, int k)
{
struct Node* temp = newNode(k);
if (q->rear == NULL)
{
q->front = q->rear = temp;
return;
}
q->rear->next = temp;
q->rear = temp;
}
void deQueue(struct Queue* q)
{
if (q->front == NULL)
{
printf("The Queue is empty.\n");
return;
}
struct Node* temp = q->front;
printf("Deleted Element: %d\n",q->front->key);
q->front = q->front->next;
if (q->front == NULL)
q->rear = NULL;
free(temp);
}
void display(struct Queue* q)
{
struct Queue* temp=q;
if(temp->front == NULL)
{
printf("The Queue is Empty.\n");
}
else
{
printf("Queue contains the following elements:\n");
while(temp->front != NULL)
{
printf("%d\t",temp->front -> key);
temp->front = temp->front -> next;
}
printf("\n");
}
}
int main()
{
struct Queue* q = createQueue();
int choice=0;
while(choice != 4)
{
printf("Choose from the following by entering the index number:\n1.Insert an element\n2.Delete an element\n3.Display the elements in queue\n4.Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
int k;
printf("Enter the element you want to insert: ");
scanf("%d",&k);
enQueue(q,k);
break;
}
case 2:
{
deQueue(q);
break;
}
case 3:
{
display(q);
break;
}
case 4:
{
printf("\nThe program has ended.");
exit(0);
break;
}
default:
{
printf("\nInvalid Input! Please try again.");
}
}
}
}
【问题讨论】:
标签: c pointers struct while-loop queue