Data Structure Problem | Stack implementation using Linked list | Best source of competitive coding


Data Structure Problem | Stack implementation using Linked list | Best source of competitive coding :
In our programming website we teach computer coding to kids and pros for free online in easy way and gives knowledge about Data structure and alogorithm in C,Java,Python
 and other programming languages that may help you land an online job and make your programmers day successfull.

We use best data structure notes and best programming resources. Here goes the article,dont forget to share with your friends 😃
Implementing stack using linked:
A stack can be implemented with the help of the linked list & also with the help of the array;here we discuss about the linked list case;more precisely singly linked list;the code is as follows::::
// stack implementation using linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *top=NULL;
void push(int );
void pop();
void display();
main()
{
int ch,item;
while(1)
{
printf("1.Push an element\n2.Pop an element\n3.Display the stack\n4.Exit\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the element to be pushed:");
scanf("%d",&item);
push(item);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
}
void push(int a)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node)); //allocating memory for the element to be pushed
temp->data=a;
temp->next=top; 
top=temp; //now the pushed elemnt is the top of the stack
}
void pop()
{
struct node *temp;
temp=top;
if(top==NULL)
{
printf("Stack is empty");
}
else
{
temp=top;//temp points to top of stack=>1st element of linked list
printf("Poped element is %d:",temp->data); //1st element(element to be poped) is printed 
top=top->next; //now 2nd element of the stack is now the 1st element of stack
free(temp);
}
}
void display()
{
struct node *temp;
temp=top;
if(top==NULL)
{
printf("stack is empty!");
}
else
{
printf("Elements of stack are:\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
printf("\n");
}

Post a Comment

0 Comments