0

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);
}
ichigo14
  • 63
  • 5
  • 2
    This function void init(node *t){//initialize t=NULL; } does not make a sense and has no effect. That is after these two lines node *top; init(top); the pointer top is not initialized. It is enough to write node *top = NULL; – Vlad from Moscow Nov 25 '20 at 21:39
  • Many problems. In is this in `pop`: `s=s->next;` The `s` variable is local to the function. Setting it does not change the caller's value. Result is freed memory remains in the caller's stack structures. – kaylum Nov 25 '20 at 21:40
  • Also, in `sortStack`, the variable `node *temp;` is never initialized. – 001 Nov 25 '20 at 21:41

0 Answers0