【发布时间】:2016-08-17 08:39:16
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
struct nodeStack{
char operator;
struct nodeStack *next;
};
typedef struct nodeStack node;
node *start=NULL;
node *tail=NULL;
int top=-1;
int isEmpty()
{
if(top==-1)
return 1;
}
void push(char c){
node *tempNode,*tail;
tempNode=(node*) malloc(sizeof(node));
if(tempNode==NULL){
printf("Memory Unvailable\n");
return;
}
tempNode->operator=c;
if(start==NULL){
start=tempNode;
tail=start;
tempNode->next=NULL;
top++;
}
else{
tail->next=tempNode;
tempNode->next=NULL;
tail=tail->next;
top++;
}
}
/*
struct node* pop(){
if(top==-1){
printf("stack is empty");
return;
}
else
{
node *temp;
temp=start;
while(temp->next!=tail){
temp->next=NULL;
free(tail);
tail=temp;
}
}
}*/
void displayStack(){
node *i;
for(i=start;i!=tail;i=i->next){
printf("%c -> ",i->operator);
}
}
int main(){
int i;
int flag=1;
char choice='y';
printf("pushing data into the stack......");
while(flag==1){
char ch;
printf("enter a character\n");
scanf(" %c",&ch);
push(ch);
printf("want to push more operator (y\n)");
scanf(" %c",choice);
if(choice=='y')
flag=1;
else
flag=0;
}
displayStack();
return 0;
}
当我尝试运行它时,它给了我分段错误。 它只接受一个输入而不接受进一步的输入,同时它给出了分段错误
当我尝试运行它时,它给了我分段错误。 它只接受一个输入而不接受进一步的输入,同时它给出了分段错误
【问题讨论】:
-
注意:你不需要尾指针。无论如何,不是为了堆栈。
-
您没有使用任何内存分配“开始”,这就是它给出“分段错误”的原因。另外,您已经在 push 方法中声明了“tail”;不需要!
-
@kiner_shah
start在start==NULL时由tempNode初始化。所以这不是问题的原因 -
请将
else语句添加到isEmpty函数中。 -
@FredrickGauss 不错。照原样,如果
top != 1,该函数调用UB。那么,OP,您是否希望编译器猜测您要返回的值是什么?您可能想要的只是return top == -1将条件转换为布尔返回值。我的意思是,你甚至不在这里使用那个功能,但如果你使用了,它很快就会引起麻烦。
标签: c linked-list stack