Pertemuan 2

Pada pertemuan kedua kelas besar kemarin saya belajar mengenai cara membuat linked list di C. Setelah saya mempelajarinya kemarin, saya juga mencoba membuat linked list buatan saya sendiri. Berikut codingan linked list saya :

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

struct Node{
int test;
char nama[1000];
struct Node *next;
}*head,*curr,*tail,*temp1,*temp2;

void pushhead(int a,char nama[]){
curr = (struct Node*)malloc(sizeof(struct Node));
curr -> test = a;
strcpy(curr->nama,nama);
if(head==NULL){
head=curr;
tail=curr;
tail->next=NULL;
}
else{
curr->next = head;
head = curr;
}
}

void pushtail(int a,char nama[]){
curr = (struct Node*)malloc(sizeof(struct Node));
curr -> test = a;
strcpy(curr->nama,nama);
if(head==NULL){
head=curr;
tail=curr;
tail->next=NULL;
}
else{
tail->next = curr;
curr->next=NULL;
tail = curr;
}
}

void poptail(){
curr=head;
while(curr->next->next!=NULL){
curr=curr->next;
}
free(tail);
tail=curr;
tail->next=NULL;
}

void pophead(){
curr=head;
curr=curr->next;
free(head);
head=curr;
}

void print(){
curr=head;
while(curr!=NULL){
printf("%d %s\n",curr->test,curr->nama);
curr=curr->next;
  }
}

void pushmiddle(int a,char nama[],int urutan1,int urutan2){
curr = (struct Node*)malloc(sizeof(struct Node));
curr -> test = a;
strcpy(curr->nama,nama);
temp1=temp2=head;
for(int i=1;i<urutan1;i++){
temp1=temp1->next;
}
temp2=temp1->next;
temp1->next=curr;
curr->next=temp2;
}

void popmiddle(int urutan){
curr=head;
for(int i=1;i<urutan-1;i++){
curr=curr->next;
}
temp1=curr->next;
curr->next=temp1->next;
free(temp1);
}

int main(){
pushtail(1,"a");
pushtail(2,"b");
pushtail(3,"c");
pushtail(4,"d");
pushtail(5,"e");
pushtail(6,"f");
pushtail(7,"g");
pushtail(8,"h");
pushhead(0,"bukan huruf");
pophead();
poptail();
popmiddle(4);
pushmiddle(100,"ivano",3,4);
print();
}

Komentar

Postingan populer dari blog ini

AVL Tree

HEAP and TRIES

Summary