Commits

Nick Raptis committed 0e602a0

Exercises for week 4 (08/04/2011)

- Queue implementation

Comments (0)

Files changed (2)

1550_Ask3_stack.c

         x = stack[head-1];
         head--;
         check = 0;
+        return x;
     }
     else
     {

1550_Ask4_queue.c

+/*
+  Name: Raptis Nikolaos
+  AM: 1550
+  Omada: Paraskeyi 16-18 
+  Date: 08/04/11 16:44
+  Description: Ylopoiisi ouras
+*/
+#include <stdio.h>
+#include <stdlib.h>
+#define N 5
+
+int queue[N], head=0, back=-1, counter=0, check;
+void printq(void);
+void enqueue(int);
+int dequeue(void);
+
+main()
+{
+    int choice, x;
+    
+    do
+    {
+        printf("0: Ektypwsi ouras\n1: Eisagwgi stin oura\n");
+        printf("2: Trabigma apo oura\n3: Eksodos\nDwste entoli...\n");
+        scanf("%d", &choice);
+        printf("\n");
+        
+        if(choice==0) //print queue
+        {
+            printq();
+        }
+        else if(choice==1) //enqueue
+        {
+            printf("Arithmos gia eisagwgi : ");
+            scanf("%d", &x);
+            enqueue(x);
+            if(check==1)
+            {
+                printf("Sfalma: H oura einai gemati\n");
+            }
+            else
+            {
+                printf("Eisagwgi epityxis\n");
+            }
+        }
+        else if(choice==2) //dequeue
+        {
+            x = dequeue();
+            if(check==1)
+            {
+                printf("Sfalma: H oura einai adeia\n");
+            }
+            else
+            {
+                printf("Htan: %d\n", x);
+            }
+        }
+        else if(choice==3) //exit
+        {
+            printf("Eksodos!\n");
+        }
+        else
+        {
+            printf("Lathos entoli\n");
+        }
+        
+        printf("\n\n");
+    } while(choice!=3);
+
+    system("pause");    
+}
+
+void printq(void)
+{
+    int i;
+    printf("oura:\n");
+    for(i=0; i<N; i++)
+    {
+        if(i==head)
+            printf("H");
+        printf("%d",queue[i]);
+        if(i==back)
+            printf("B");
+        printf(" ");
+    }
+    printf("\n");
+}
+
+void enqueue(int x)
+{
+    if(counter<N)
+    {
+        if(back < N-1)
+            back++;
+        else
+            back = 0;
+        queue[back] = x;
+        counter++;
+        check = 0;
+    }
+    else
+    {
+        check = 1;
+    }
+}
+
+int dequeue(void)
+{
+    int x;
+    if(counter>0)
+    {
+        x = queue[head];
+        if(head < N-1)
+            head++;
+        else
+            head = 0;
+        counter--;
+        check = 0;
+        return x;
+    }
+    else
+    {
+        check = 1;
+    }
+}