Created
November 20, 2015 11:24
-
-
Save serhii-shnurenko/30302b315015ba1f7573 to your computer and use it in GitHub Desktop.
This is how stack and queue works in C programming language
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
#include <stdio.h> | |
struct QueueNode{ | |
char value; | |
struct QueueNode* next; | |
}; | |
int main() | |
{ | |
char str[] = "Queue is working like FIFO"; | |
//pointer to the head | |
struct QueueNode* first; | |
//allocating memory for head of the queue | |
first = malloc(sizeof(struct QueueNode)); | |
//pushing char sequence in queue | |
struct QueueNode * prev; | |
struct QueueNode * curr=first; | |
printf("Starting to push all of the elements to queue: \n"); | |
int i; | |
for(i=0;i<sizeof(str);i++){ | |
curr->value = str[i]; | |
printf("Pushing to queue %c \n",curr->value); | |
//saving pointer to current curr before rewriting curr with new value | |
prev = curr; | |
//rewriting curr with adress to new free portion of memory | |
curr = malloc(sizeof(struct QueueNode)); | |
prev->next = curr; | |
//NULL next pointer means the end of the Queue | |
curr->next = NULL; | |
} | |
//setting current pointer to he HEAD | |
curr=first; | |
printf("\n\nPoping all element from queue:\n"); | |
while(curr->next!=NULL){ | |
printf("Poping from queue %c \n",curr->value); | |
//deleting node | |
struct QueueNode* temp = curr; | |
curr = curr->next; | |
free(temp); | |
} | |
return 0; | |
} |
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
#include <stdio.h> | |
struct StackNode{ | |
char value; | |
struct StackNode* prev; | |
}; | |
int main() | |
{ | |
char str[] = "Stack is working like FILO"; | |
//pointer we will working with | |
struct StackNode* node; | |
//Creating first node in StackNode | |
//it will be newer used | |
node = malloc(sizeof(struct StackNode)); | |
node->prev = NULL; | |
//pushing char sequence in stack | |
int i; | |
printf("Starting to push all of the elements to stack: \n"); | |
for(i=0;i<sizeof(str);i++){ | |
struct StackNode * temp = node; | |
node = malloc(sizeof(struct StackNode)); | |
node->value = str[i]; | |
node->prev = temp; | |
printf("Pushing to stack %c \n",node->value); | |
} | |
printf("\n\nPoping all element from stack:\n"); | |
while(node->prev!=NULL){ | |
printf("Poping from stack %c \n",node->value); | |
//deleting node | |
struct StackNode* temp = node; | |
node = node->prev; | |
free(temp); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment