c-使用链表实现堆栈



我得到了一个"函数应该返回一个值"0";Turbo C++中代码的第91行出现错误,请帮助我,因为我必须提交我的项目,我知道Turbo C++是一个非常旧的编译器,但这是我们大学老师建议的,所以我不能在中做任何事情

#include <stdio.h>
#include <conio.h>
struct stack
{
int element;
struct stack *next;
} * top;
void push(int);
int pop();
void display();
void main()
{
int num1, num2, choice;
while (1)
{
clrscr();
printf("Select a choice from the following:");
printf("n[1] Push an element into the stack");
printf("n[2] Pop out an element from the stack");
printf("n[3] Display the stack elements");
printf("n[4] Exitn");
printf("ntYour choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("ntEnter the element to be pushed into the stack: ");
scanf("%d", &num1);
push(num1);
break;
}
case 2:
{
num2 = pop();
printf("nt%d element popped out of the stacknt", num2);
getch();
break;
}
case 3:
{
display();
getch();
break;
}
case 4:
exit(1);
break;
default:
printf("nInvalid choice !n");
break;
}
}
}
void push(int value)
{
struct stack *ptr;
ptr = (struct stack *)malloc(sizeof(struct stack));
ptr->element = value;
ptr->next = top;
top = ptr;
return;
}
int pop()
{
if (top == NULL)
{
printf("nSTACK is Empty.");
getch();
exit(1);
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}
void display()
{
struct stack *ptr1 = NULL;
ptr1 = top;
printf("nThe various stack elements are:n");
while (ptr1 != NULL)
{
printf("%dt", ptr1->element);
ptr1 = ptr1->next;
}
}

编译器正在抱怨,因为在if语句之外没有return语句。尽管您在if分支中调用exit,但从语法上讲,这只是另一个函数调用在结构上,编译器会看到一条路径,在该路径中,您可以在没有return语句的情况下到达函数体的结束}

您希望确保returnif-else语句的主体之外是可访问的,最好的方法是将else分支完全从语句中取出:

int pop( void )
{
int temp;
if ( !top )
{ 
fputs( "Stack is empty", stderr );
exit( 1 );
}
temp = top->element;
top = top->next;
return temp;
}

您可以如下更改pop函数(假设您没有将-1存储为堆栈中的元素(

int pop()
{
if (top == NULL)
{
printf("nSTACK is Empty.");
getch();
return -1;// or other invalid value which indicates stack empty
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}

在您呼叫的地方修改为以下

case 2:
{
num2 = pop();
if(num2 != -1) {
printf("nt%d element popped out of the stacknt", num2);
getch();
}else{
printf("Stack is Emptyn");
exit(1);
}
break;
}

最新更新