Skip to main content

pushHead dan popHead

Di kelas besar pada tanggal 3 Maret 2020 saya belajar tentang pushHead dan popHead, berikut adalah contoh kodingannya :
#include<stdio.h>
#include<stdlib.h>

struct data{
int angka;
data* next;
}*head = NULL, *tail = NULL;

void pushHead(int angka){
struct data *curr = (struct data*) malloc(sizeof(struct data));
curr->angka = angka;
if(head == NULL){
head = tail = curr;
}else{
curr->next = head;
head = curr;
tail->next = NULL;
}
}

void popHead(){
struct data *curr = (struct data*) malloc(sizeof(struct data));
if(head == NULL){
head = tail = NULL;
}else{
curr = head;
head = head->next;
free(curr);
tail->next = NULL;
}
}

void print(){
struct data* curr = head;
while(curr!=NULL){
printf("%d\n", curr->angka);
curr = curr->next;
}
}

int main(){
pushHead(20);
pushHead(18);
print();
popHead();
print();
return 0;
}

Comments

Popular posts from this blog

Linked List

Linked List In this blog I want to explain to you what Linked List is. There are 3 types of Linked List that commonly used by people. The first one and the simplest one is Singly Linked List, and then there's also Circular Singly Linked List and Doubly Linked List. But in this blog I'll only cover Singly and Doubly Linked List only. 1. Singly Linked List     Singly Linked List is the simplest method of Linked List because of the simplicity the code have, the first thing you need to do to make a Linked List of course making a struct and make sure declare head and tail. What is head and tail? Head means the first data from the front and Tail means the last data that you can input.   Example : #include<stdio.h> struct Mahasiswa{ int nim; char nama[100]; double ipk; Mahasiswa *next; }*head = 0, *tail = 0; After you declare the struct make sure you use malloc to allocate the memory to the struct for the dynamic memory, which mean you don't need to declar...