Contoh stack 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 Stack {
struct Elemen *top;
} Stack;
void display(Stack);
void push(int value, Stack *Stack);
void pop(Stack *Stack);
int main(){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));;
int menu;
char opsi;
int value;
Stack Stack;
Stack.top = NULL;
do {
printf("===============menu===============\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n");
printf("==================================\n");
printf("Pilih menu : ");scanf("%d", &menu);
printf("----------------------------------------\n");
if (menu == 1){
printf("Push \n");
printf("----------------------------------------\n");
do {
printf("Value : ");
scanf("%d", &value);fflush(stdin);
push(value, &Stack);
printf("berhasil !\n");
printf("Push again ? [Y/N] : ");
scanf("%c", &opsi);fflush(stdin);
printf("\n");
} while (opsi == 'Y' || opsi == 'y');
} else if (menu == 2){
printf("Pop \n");
printf("----------------------------------------\n");
if (Stack.top == NULL){
printf("\nData belum ada !\n");
} else {
pop(&Stack);
printf("\n berhasil !\n");
}
} else if (menu == 3){
display(Stack);
} else if (menu == 4){
printf("Keluar\n");
} else {
printf("Menu tidak tersedia !\n");
}
} while (menu != 4);
}
void display(Stack Stack){
if(Stack.top == NULL){
printf("\nData Kosong !\n");
} else {
printf("-> Isi Data : \n");
Elemen *current = Stack.top;
while(current != NULL){
printf("%d \n",current->Data.value);
current = current->next;
}
}
}
void push(int value, Stack *Stack){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));
current->Data.value = value;
if(Stack->top == NULL){
Stack->top = current;
current->next = NULL;
current = NULL;
} else {
current->next = Stack->top;
Stack->top = current;
current = NULL;
}
}
void pop(Stack *Stack){
Elemen *current = (Elemen*) malloc(sizeof(Elemen));
if(Stack->top->next != NULL){
current = Stack->top;
Stack->top = current->next;
} else {
Stack->top = NULL;
}
free(current);
current = NULL;
}
link terkait:
contoh queue menggunakan linked list bahasa c
contoh queue menggunakan array bahasa c
contoh stack menggunakan array bahasa c
0 comments:
Post a Comment