I have a program where i implement a stack with a linked list and sort it with another temporary stack.I think it's supposed to work but it outputs segmentation fault.
This part is the declaration of the stack functions
typedef struct Node{
int val;
struct Node*next;
}node;
void init(node *t){//initialize
t=NULL;
}
int isempty(node *n){//check if empty
if(n==NULL){return 1;}
return 0;
}
void push(node *t,int val){
node *temp;
temp=malloc(sizeof(node));
if(temp==NULL){
exit(0);
}
temp->val=val;
temp->next=t;
t=temp;
}
void pop(node *s){
int t;
node *temp;
temp=s;
t=temp->val;
s=s->next;
free(temp);
}
int topSt(node *s){//returns top of the stack
return s->val;
}
The function where the stack gets sorted
node *sortStack(node *input){//sorting the stack
node *temp;
int t;
while(!isempty(input)){
t=topSt(input);
pop(input);
while(!isempty(temp) && topSt(temp)>t){
push(input,topSt(temp));
pop(temp);
}
push(temp,t);
}
return temp;
}
Display function to print the elements of the stack
void display(node *head){//display the stack's elements
while(head != NULL){
printf("%d\n", head->val);
head=head->next;
}
}
The main function
int main(){
node *top;
init(top);
push(top,9);
push(top,45);
push(top,21);
push(top,5);
node *sorted=sortStack(top);
display(sorted);
}