-
Notifications
You must be signed in to change notification settings - Fork 302
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
stackUsingArray.c: Added stack using array in C
Added stack data structure code in C. Closes #315
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |