Stack Implementation in C
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
void display_stack( struct node** head);
int count( struct node **head);
void push( struct node** head, int val);
int pop( struct node** head);
int main(){
struct node *head;
head = NULL;
int item;
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
display_stack( &head);
printf("The length of [STACK] is %d\n", count(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The length of [STACK] is %d\n", count(&head));
display_stack( &head);
return 0;
}
void display_stack( struct node** head){
struct node* temp = *head;
while( temp != NULL ){
printf("The element in [STACK] is %d\n", temp->value);
temp = temp->next;
}
}
int count( struct node **head){
struct node *temp;
temp = *head;
int count = 0;
while( temp != NULL){
count++;
temp = temp->next;
}
return count;
}
void push( struct node** head, int val){
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->value = val;
temp->next = *head;
*head = temp;
}
int pop( struct node** head){
if( *head == NULL){
printf( "The stack is empty");
return 0;
} else {
struct node *temp = *head;
*head = (*head)->next;
return temp->value ;
}
}
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
void display_stack( struct node** head);
int count( struct node **head);
void push( struct node** head, int val);
int pop( struct node** head);
int main(){
struct node *head;
head = NULL;
int item;
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
display_stack( &head);
printf("The length of [STACK] is %d\n", count(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The element popped of [STACK] is %d\n", pop(&head));
printf("The length of [STACK] is %d\n", count(&head));
display_stack( &head);
return 0;
}
void display_stack( struct node** head){
struct node* temp = *head;
while( temp != NULL ){
printf("The element in [STACK] is %d\n", temp->value);
temp = temp->next;
}
}
int count( struct node **head){
struct node *temp;
temp = *head;
int count = 0;
while( temp != NULL){
count++;
temp = temp->next;
}
return count;
}
void push( struct node** head, int val){
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->value = val;
temp->next = *head;
*head = temp;
}
int pop( struct node** head){
if( *head == NULL){
printf( "The stack is empty");
return 0;
} else {
struct node *temp = *head;
*head = (*head)->next;
return temp->value ;
}
}
No comments:
Post a Comment