【发布时间】:2020-01-16 09:30:06
【问题描述】:
我用 C 语言编写了一个代码来使用 LinkedList 算法实现堆栈。这是代码............
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
struct listNode {
int data;
struct listNode *next;
};
struct stack{
struct stack *top;
};
struct stack *createstk(){
struct stack *stk;
stk=malloc(sizeof(struct stack));
stk->top=NULL;
return stk;
}
void push(struct stack *stk,int data){
struct listNode *temp;
temp=malloc(sizeof(struct listNode));
if(!temp){
printf("heap overflow");
return;
}
temp->data=data;
temp->next=stk->top;
stk->top=temp;
}
int pop(struct stack *stk){
if(isEmpty(stk))
return INT_MIN;
int data;
struct listNode *temp;
temp= stk->top;
stk->top=stk->top->next;
data=temp->data;
delete(temp);
return data;
}
int peek(struct stack *stk){
if(isEmpty(stk))
return INT_MIN;
return stk->top->data;
}
int isEmpty(struct stack *stk){
return stk->top==NULL;
}
void deleteStack(struct stack *stk){
struct listNode *temp,*p;
p=stk->top;
while(p){
temp=p->next;
p=p->next;
free(temp);
}
free(stk);
}
int main(){
int i=0;
struct stack *stk=createstk();
for(i=0;i<=10;i++)
push(stk,i);
printf("Top Element is %d",peek(stk));
for(i=0;i<=10;i++){
printf("popped element is %d",pop(stk));
}
if(isEmpty(stk))
printf("stack is empty");
else
printf("stack is not empty");
deleteStack(stk);
return 0;
}
[警告]来自不兼容指针类型的赋值。 正如您在图片中看到的那样。我是编码世界的新手,第一次遇到这个错误。这就是为什么我不知道该怎么办。请告诉我...
【问题讨论】:
-
struct listNode *temp;创建temp作为指向listNode的指针(temp->next相同)。您尝试temp->next=stk->top;,它尝试分配stk->top(类型指针指向struct stack)。您不能将指向struct stack的指针分配给指向listNode的指针。 (您始终有类似的错误) -
temp->next 指向与 stk->top 不同的类型
标签: c data-structures linked-list stack singly-linked-list