C program gurnuti naprijed polje

Kako napisati C program gurnuti naprijed polje



#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define SIZE 8

#ifndef DEBUG
#define DEBUG(...) printf(__VA_ARGS__)
#endif

int size = 0;

void swap(int *a, int *b)
{
 int temp = *a;
 *a = *b;
 *b = temp;
}

int enqueue(int queue[], int head, int *tail, int val) {
    if ((*tail+1)%SIZE==head) return -1;

    queue[*tail] = val;
    *tail = (*tail+1)%SIZE;
    
    size++;
    return 0;
}

int dequeue(int queue[], int *head, int tail) {
    if (*head==tail) return -1;

    DEBUG("Obrisan element %d.\n", queue[*head]);
    *head = (*head + 1)%SIZE;
    
    size--;
    return 0;
}

int print(int queue[], int head, int tail) {
    int i;
    
    DEBUG("H: %d\n", head);
    DEBUG("T: %d\n", tail);

    if (tail==head) return -1;

    for (i=head; i!=tail; i=(i+1)%SIZE) {
        printf("%d ", queue[i]);
    }
    printf("\n");
    return 0;
}


int poguraj_naprijed(int *queue, int *head, int *tail, int br_el) 
{
 int i = 0;
 
 if(*head == *tail)
 {
  return 0;
 }
 
 if(*tail - 1 == *head)
 {
  return 0;
 }
 
 if(br_el > size)
 {
  return 0;
 }
 
 if(br_el <= 1)
 {
  return 0;
 }
 
 int count = 0;
 int prethodni = 0;
 
 DEBUG("H: %d\n", *head);
    DEBUG("T: %d\n", *tail);
 
 for (i=*head; i!=*tail; i=(i+1)%SIZE) 
 {
  count++;
  
  DEBUG("Count: %d\n", count);
        DEBUG("Iterator: %d\n", i);
  if(count == br_el)
  {
   swap(&queue[prethodni], &queue[i]);
   break;
  }
  prethodni = i;
    }
 
 return 0;
}


int main() {
    int val, ret_val, menu_choice;
    int *queue, head=0, tail=0;
    char c;

    queue = (int *)malloc(sizeof(int) * SIZE);
    setbuf(stdout, NULL);
    
    //DEBUG("\n1 opis funkcije (ime_funkcije)");
    DEBUG("\n2 dodaj(enqueue)\n3 brisi (dequeue)\n4 ispis (print)\n5 izlaz\n");
    do {
        menu_choice = 0;
        scanf("%d", &menu_choice);
        switch (menu_choice) {
            case 1:
    scanf("%d", &val);
                poguraj_naprijed(queue, &head, &tail, val);
                break;
            case 2:
                scanf("%d", &val);
                ret_val = enqueue(queue, head, &tail, val);
                if(ret_val==-1) DEBUG("Red je pun.\n");
                break;
            case 3:
                ret_val = dequeue(queue, &head, tail);
                if(ret_val==-1) DEBUG("Red je prazan.\n");
                break;
            case 4:
                ret_val = print(queue, head, tail);
                if(ret_val==-1) DEBUG("Red je prazan.\n");
                break;
            case 5:
                break;
            default:
                while((c = getchar()) != '\n' && c != EOF);
        }
    } while(menu_choice!=5);

    free(queue);
    return 0;
}


Learn More :