【发布时间】:2020-02-04 01:36:22
【问题描述】:
我在链表、堆栈和队列中经常遇到这些错误。如果有人能指出我一次又一次犯的错误,那就太好了。
这是我编写的代码。
#include <stdio.h>
#include <malloc.h>
struct Node
{
int data;
struct Node* next;
}*front=NULL,*rear=NULL;
void enqueue(struct Node *front,struct Node *rear,int ele)
{
struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
struct Node* ptr=front;
if (temp==NULL)
printf("Overflow");
else
{
if (front==NULL)
{
temp->data=ele;
temp->next=NULL;
front=temp;
printf("%d",front->data);
}
else
{
printf("Srishti");
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
temp->next=front;
ptr->next=temp;
rear=temp;
}
}
}
void dequeue()
{
struct Node *temp=front;
if(front!=NULL && front->next!=NULL)
{
rear->next=front->next;
front=front->next;
}
}
void display()
{
struct Node *temp=front;
while(temp->next!=front)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("%d",rear->data);
}
void main()
{
int n,i;
for(i=0;i<3;i++)
{
printf("Enter Element");
scanf("%d",&n);
enqueue(front,rear,n);
}
display();
}
我看到的输出总是Segmentation Fault (core dumped)。我已经尝试在多台机器和编译器上运行代码,但仍然没有区别。
【问题讨论】:
-
您应该包含
stdlib.h而不是malloc.h-- 后者不可移植。 -
另外,不要使用
void main()。请改用int main(void)。 -
@JL2210 进行了更改。还是没有解决问题
-
我不是说他们会。你的代码有比这更多的错误。这些只是风格变化。
标签: c linked-list queue