kybookie
kybookie

Reputation: 41

Empty stack of linked list

I am trying to figure the way to empty stack for linked list. I found a way but this way is only work for array stack

void empty(StackPtr S)
{
    S -> top = -1;
}

my guess is to use

while(!isEmpty(s))

which the function isEmpty will check if the stack is empty or not. Then I'm stuck :(

Edit: The way I push it:

    void push(StackPtr S, StackData d) /*adds the top element*/
{
    NodePtr np = (NodePtr)malloc(sizeof(Node));
    np -> data = d;
    np -> next = S -> top;
    S -> top = np;

}

Upvotes: 1

Views: 1232

Answers (1)

Ajay
Ajay

Reputation: 4971

This is a basic program for implementing stack data structure and its operations. Hope it will help you.

#include<stdio.h>
#include<stdlib.h>
#define INT_MIN -99;

struct Stack{
    int data;
    struct Stack *next;
};

struct Stack *CreateStack(){
    return NULL;
}

void Push(struct Stack **top,int data){
    struct Stack *temp;
    temp=malloc(sizeof(struct Stack));

    if(!temp)
        return NULL;

    temp->data = data;
    temp->next= *top;

    *top=temp;
}

int IsEmptyStack(struct Stack *top){
    return top==NULL;
}

int Pop(struct Stack **top){
    int data;
    struct Stack *temp;

    if(IsEmptyStack(*top))
        return INT_MIN;

    temp=*top;
    *top=temp->next;
    data=temp->data;
    printf("%d",data);
    free(temp);
    return data;
}

int Top(struct Stack *top){
    if(IsEmptyStack(top))
        return INT_MIN;

    return top->next->data;
}

void DeleteStack(struct Stack **top)
{
    struct Stack *temp,*p;
    p=*top;
    while(p->next){
        temp=p->next;
        p->next=temp->next;
        free(temp);
    }

    free(p);
}

void main(){

    struct Stack *s=CreateStack();
    Push(&s,5);
    Push(&s,15);
    Push(&s,52);
    Pop(&s);
    Pop(&s);
    Push(&s,35);
    Push(&s,53);
    Pop(&s);
    Push(&s,45);

}

Upvotes: 2

Related Questions