Contoh queue menggunakan linked list Bahasa c
#include <stdio.h>
#include <stdlib.h>
typedef struct Data {
int value;
} Data;
typedef struct Elemen {
struct Data Data;
struct Elemen *next;
} Elemen;
typedef struct Queue {
struct Elemen *front;
struct Elemen *rear;
} Queue;
void display(Queue);
void insert(int value, Queue *Queue);
void deleteQueue(Queue *Queue);
int main(){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));;
int menu;
char opsi;
int value;
Queue Queue;
Queue.front = NULL;
do {
printf("===============menu===============\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("==================================\n");
printf("Pilih menu : ");scanf("%d", &menu);
printf("----------------------------------------\n");
if (menu == 1){
printf("Insert \n");
printf("----------------------------------------\n");
do {
printf("Value : ");
scanf("%d", &value);fflush(stdin);
insert(value, &Queue);
printf("berhasil !\n");
printf("Insert again ? [Y/N] : ");
scanf("%c", &opsi);fflush(stdin);
printf("\n");
} while (opsi == 'Y' || opsi == 'y');
} else if (menu == 2){
printf("Delete \n");
printf("----------------------------------------\n");
if (Queue.front == NULL){
printf("\nData belum ada !\n");
} else {
deleteQueue(&Queue);
printf("\n berhasil !\n");
}
} else if (menu == 3){
display(Queue);
} else if (menu == 4){
printf("Keluar\n");
} else {
printf("Menu tidak tersedia !\n");
}
} while (menu != 4);
}
void display(Queue Queue){
if(Queue.front == NULL){
printf("\nData Kosong !\n");
} else {
printf("-> Isi Data : \n");
Elemen *current = Queue.front;
while(current != NULL){
printf("%d \n",current->Data.value);
current = current->next;
}
}
}
void insert(int value, Queue *Queue){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));
current->Data.value = value;
if(Queue->front == NULL){
Queue->front = current;
Queue->rear = current;
current->next = NULL;
current = NULL;
} else {
Queue->rear->next = current;
Queue->rear = current;
current->next = NULL;
current = NULL;
}
}
void deleteQueue(Queue *Queue){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));
if(Queue->front->next != NULL){
current = Queue->front;
Queue->front = current->next;
} else {
Queue->front = NULL;
}
free(current);
current = NULL;
}
link terkait:
contoh stack menggunakan array bahasa c
contoh stack menggunakan linked list bahasa c
contoh queue menggunakan array bahasa c
0 comments:
Post a Comment