Advertisement
r4lovets

DS1

Nov 14th, 2019
856
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #define STACK_SIZE 5
  3.  
  4. struct stackElement
  5. {
  6.     int value;
  7.     struct stackElement* prev;
  8.     struct stackElement* next;
  9. };
  10.  
  11. struct stackElement* pushStack(struct stackElement* stackPointer, int value) {
  12.     if (stackPointer == NULL) {
  13.         stackPointer = (struct stackElement*) malloc(sizeof(struct stackElement));
  14.         stackPointer->prev = NULL;
  15.         stackPointer->next = NULL;
  16.     }
  17.     else {
  18.         struct stackElement* newElement;
  19.         newElement = (struct stackElement*) malloc(sizeof(struct stackElement));
  20.         stackPointer->next = newElement;
  21.         newElement->prev = stackPointer;
  22.         newElement->next = NULL;
  23.         stackPointer = newElement;
  24.     }
  25.  
  26.     stackPointer->value = value;
  27.     return stackPointer;
  28. }
  29.  
  30. struct stackElement* popStack(struct stackElement* stackPointer, int* value) {
  31.     if (stackPointer->prev == NULL) {
  32.         *value = stackPointer->value;
  33.         free(stackPointer);
  34.         stackPointer = NULL;
  35.     }
  36.     else {
  37.         *value = stackPointer->value;
  38.         stackPointer = stackPointer->prev;
  39.         free(stackPointer->next);
  40.         stackPointer->next = NULL;
  41.     }
  42.     return stackPointer;
  43. }
  44.  
  45. void printStack(struct stackElement* stackPointer) {
  46.     int counter = 0;
  47.     while (stackPointer != NULL) {
  48.         printf("Value[%d]: %d\n", counter, stackPointer->value);
  49.         stackPointer = stackPointer->prev;
  50.         counter++;
  51.     }
  52. }
  53.  
  54. int main() {
  55.     puts("Source stack:");
  56.     struct stackElement* stack = NULL;
  57.     struct stackElement* posStack = NULL;
  58.     struct stackElement* negStack = NULL;
  59.    
  60.     for (int i = 0; i < STACK_SIZE; i++) {
  61.         int temp = 0;
  62.         printf("Enter value: ");
  63.         scanf_s("%d", &temp);
  64.         fseek(stdin, 0, SEEK_SET);
  65.         stack = pushStack(stack, temp);
  66.     }
  67.  
  68.     for (int i = 0; i < STACK_SIZE; i++) {
  69.         int temp = 0;
  70.         stack = popStack(stack, &temp);
  71.         if (temp < 0) negStack = pushStack(negStack, temp);
  72.         if (temp > 0) posStack = pushStack(posStack, temp);
  73.     }
  74.  
  75.     puts("");
  76.  
  77.     puts("Positive stack:");
  78.     printStack(posStack); puts("");
  79.  
  80.     puts("Negative stack:");
  81.     printStack(negStack); puts("");
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement