Dynamic Stack C program - DSA

Write a c program to create c program.

#include<stdio.h>
typedef struct node
{
    int info;
    struct node *next;
} node;
node *top;

void push(int num)
{
    node *newnode;
    newnode=(node*)malloc(sizeof(node));
    newnode->info=num;
    newnode->next=NULL;

    newnode->next=top;
    top=newnode;
}
int pop()
{
    int num;
    num=top->info;
    top=top->next;
    printf("Popped value:%d\n",num);
}
int isempty()
{
    return top==NULL;
}
int init()
{
    top=NULL;
}
int peek()
{
  return top->info;
}

int main()
{
    init();
    int choice,num;
    do
    {
        printf("1.Push\n2.Pop\n3.Peek\n4.Exit\n");
        printf("Enter: ");
        scanf("%d",&choice);
        switch(choice)
        {
        case 1:
            printf("Enter value to push:");
            scanf("%d",&num);
            push(num);
            break;
        case 2:
            if(!isempty())
                pop();
            else
                printf("Underflow\n");
            break;
        case 3:
            if(!isempty())
                printf("Top-> %d\n",peek());
            else
                printf("Underflow\n");
        }
    }
    while(choice!=4);
}

Output:

1.Push
2.Pop
3.Peek
4.Exit
Enter: 1
Enter value to push:23
1.Push
2.Pop
3.Peek
4.Exit
Enter: 1
Enter value to push:55
1.Push
2.Pop
3.Peek
4.Exit
Enter: 2
Popped value:55
1.Push
2.Pop
3.Peek
4.Exit
Enter: 3
Top-> 23
1.Push
2.Pop
3.Peek
4.Exit
Enter: 2
Popped value:23
1.Push
2.Pop
3.Peek
4.Exit
Enter: 2
Underflow
1.Push
2.Pop
3.Peek
4.Exit
Enter: 4

Process returned 0 (0x0)   execution time : 27.967 s
Press any key to continue.

Explaination :

//coming soon

Post a Comment

0 Comments