Stack and Queue

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

struct node{
int data;
struct node *p;
};
void push(struct node **s,int nilai){
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
temp->data = nilai;

temp->p = *s;

*s = temp;
}
void pop(struct node **s){
struct node *temp;
int nilai;
if(*s !=NULL){
temp = *s;
nilai = temp->data;
*s = temp->p;
free(temp);
return nilai;
}else{
return 1;
}
}
int main (void){
struct node *paling_atas;
paling_atas = NULL;

push(&paling_atas,10);
push(&paling_atas,20);
push(&paling_atas,30);
push(&paling_atas,40);

while(paling_atas !=NULL){
printf(“%d\n”,(paling_atas));
paling_atas = paling_atas->p;
}
getchar();
return 0;
}

Queue

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

struct node{
int data;
struct node *p;
};
void tambah_elemen(struct node **a,struct node **b,int nilai){
struct node *temp;

temp = (struct node*)malloc(sizeof(struct node));

temp->data = nilai;
temp->p = NULL;

if (*a == NULL){
*a = temp;
}else{
(*b)->p = temp;
}
*b = temp;
}
void hapus_elemen(struct node **a,struct node **b){
struct node*temp;

if(*a==NULL){
printf(“tidak terdapat elemen dalam sebuah nilai”);
}else{
temp = *a;
*a = temp->p;

free(temp);

if(*a == NULL){
*b = NULL;
}
}
}
void tampilkan_nilai(struct node *a){
int nilai;
while(a !=NULL){
nilai = a->data;
printf(“%d\n”,nilai);
a = a->p;
}
}
int main(void){
struct node *depan,*belakang;
depan = belakang = NULL;
tambah_elemen(&depan,&belakang,10);
tambah_elemen(&depan,&belakang,20);
tambah_elemen(&depan,&belakang,30);
tambah_elemen(&depan,&belakang,40);

tampilkan_nilai(depan);

printf(“nilai – nilai yang terdapat di dalam : \n”);

hapus_elemen(&depan, &belakang);

printf(“nilai – nilai yang terdapat di dalam setelah penghapusan pertama : \n”);

tampilkan_nilai(depan);

getchar();
return 0;
}

About Dx

My name is Degris
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Stack and Queue

Leave a Reply

Your email address will not be published. Required fields are marked *