Skip to content

Commit

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

Closes #315
  • Loading branch information
jadia committed Oct 14, 2018
1 parent 67e0d9b commit 3fc4661
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ 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) |
<<<<<<< HEAD
| [Stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)) | [:octocat:](stack/C ) | | [: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) |
>>>>>>> 8f2ad6f... Add stack in C to README.md
| [Linear Linked List](https://en.wikipedia.org/wiki/Linked_list) | [:octocat:](linked_list/C) | [:octocat:](linked_list/Cpp) | | [: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 3fc4661

Please sign in to comment.