๐ Daftar Isi

Stack menggunakan single linked list yang memiliki 3 elemen dan TOP (elemen teratas) mempunyai alamat 4800.
Deklarasi Stack
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node *item;
item top;
Inisialisasi Stack
void initialize()
{
top= NULL;
}
Fungsi Push
void push(int value)
{
item new_node;
new_node = (item)malloc(sizeof(struct node));
new_node->data = value;
new_node->next = top;
top = new_node;
}
Fungsi Pop
int pop()
{
if (top == NULL)
{
printf("Stack masih kosong, tidak dapat menghapus item\n");
return 0;
}
item tmp;
tmp = top;
top = top->next;
free(tmp);
return(1);
}
Fungsi Display
void display(item head)
{
if (head == NULL)
{
printf("Stack kosong\n");
}
else
{
printf("%d\n", head->data);
if (head->next != NULL)
display(head->next);
}
}
Fungsi Node Top
int displaytop()
{
return top->data;
}
Source Code Lengkap
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node *item;
item top;
void initialize()
{
top= NULL;
}
void push(int value)
{
item new_node;
new_node = (item)malloc(sizeof(struct node));
new_node->data = value;
new_node->next = top;
top = new_node;
}
int pop()
{
if (top == NULL)
{
printf("Stack masih kosong, tidak dapat menghapus item\n");
return 0;
}
item tmp;
tmp = top;
top = top->next;
free(tmp);
return(1);
}
void display(item head)
{
if (head == NULL)
{
printf("Stack kosong\n");
}
else
{
printf("%d\n", head->data);
if (head->next != NULL)
display(head->next);
}
}
int displaytop()
{
return top->data;
}
int main()
{
initialize();
display(top);
pop();
push(10);
push(20);
push(30);
push(40);
printf("Top dari stack adalah %d\n", displaytop());
pop();
printf("Top dari stack setelah pop adalah %d\n", displaytop());
display(top);
return 0;
}
Output

Materi Lengkap
Silakan baca juga beberapa artikel menarik kami tentang Stack, daftar lengkapnya adalah sebagai berikut.