Skip to content

Commit

Permalink
stackUsingArray.c: Added stack using array in C
Browse files Browse the repository at this point in the history
Added stack data structure code in C.

Closes #315
  • Loading branch information
jadia committed Oct 14, 2018
1 parent e72f3e1 commit 2c61773
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ This repository contains examples of various algorithms written on different pro
| Data Structure | C | CPP | Java | Python |
|:----------------------------------------------------------------------------------------------- |:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|:-------------------------------------:|
| [Queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) | | [:octocat:](queue/Cpp) | | |
| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | | | [:octocat:](stack/Java) | [:octocat:](stack/Python) |
| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) |[:octocat:](stack/C )| | [:octocat:](stack/Java) | [:octocat:](stack/Python) |
| [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | | | [:octocat:](linked_list/Python) |
| [AVL Tree](https://en.wikipedia.org/wiki/AVL_tree) | [:octocat:](avl_tree/C) | | [:octocat:](avl_tree/Java) | [:octocat:](avl_tree/Python) |

Expand Down
39 changes: 39 additions & 0 deletions stack/C/stackUsingArray.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#include<stdio.h>
#include<stdlib.h>

/*Using variable i to push elements then pop and print the elements. */

int main() {
void push(int *arr, int *top, int n, int i);
int pop(int *arr, int *top);
// number of elements
int n = 6;
int arr[n], top = -1;
// push all elements into the stack
for(int i = 0; i < n; i++) {
push(arr, &top, n, i);
}
printf("\n");
// pop elements one by one.
for(int i = 0; i < n; i++) {
printf("%d ", pop(arr, &top));
}
}

void push(int *arr, int *top, int n, int i) {
if(*top == n) {
printf("\nStack is full. \n");
} else {
arr[++(*top)] = i;
}
}

int pop(int *arr, int *top) {
if(*top == -1) {
printf("\n Stack empty!\n");
exit(1);
} else {
return(arr[(*top)--]);
}
return 0;
}

0 comments on commit 2c61773

Please sign in to comment.