Tuesday 3 March 2020

Linked List II

Single Linked List

Pendeklarasian struct dari sebuah node single linked list:

struct tnode {
int value;
struct tnode* next;
};

struct tnode* create_node(int value){
struct tnode* node = (struct tnode*)malloc(sizeof(struct tnode));
node->next = NULL;
node->value = value;

return node;
}
Dari single linked list di atas, dapat dilakukan beberapa operasi, yaitu:
1. Push Head
struct tnode* insert_head(struct tnode* head, int value){
struct tnode* new_node = create_node(value);
new_node->next = head;
head = new_node;
return head;

}
function di atas berfungsi untuk menginsert node baru sebagai head atau node awal.


2.Push Tail
struct tnode* insert_tail(struct tnode* head, int value){
if(head==NULL){
head = insert_head(head, value);
} else {
struct tnode* new_node = create_node(value);
struct tnode* temp = head;

while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new_node;
}
return head;

}
function di atas berfungsi untuk menginsert node baru sebagai tail atau node akhir.


3.Pop Head
struct tnode* delete_head(struct tnode* head){
struct tnode* temp = head;
head = head->next;
free(temp);

return head;

}
function di atas berfungsi untuk mendelete node head.


4.Pop Tail
struct tnode* delete_tail(struct tnode* head){
struct tnode* temp = head;
struct tnode* temp2 = head->next;

if(temp2==NULL){
head = NULL;
free(temp);
} else {
while(temp2->next!=NULL){
temp = temp->next;
temp2 = temp2->next;
}
temp->next = NULL;
free(temp2);
}
return head;

}
function di atas berfungsi untuk mendelete note tail.



No comments:

Post a Comment