E N D
Nama : Christoffel Daniel Y. Tambunan NIM : 211401040 Kom : C 1.Buatlah sebuah linked list 3 elemen dengan c++ 2.Buatlah representasi visual linked list 3.Jelaskan bagaimana anda akan menghapus element linked list yang berada di tengah Jawaban : Jawaban no. 1 & 3: #include <iostream> #include <stdlib.h> using namespace std; struct node { int data; struct node *link; }; void deletemiddle(node *head){ node *current=head->link; node *previous=head; previous->link=current->link; delete(current); } void printnode(node *head){ int i=1; node * current=head; while(current!=NULL){ cout<<"Data node ke-"<<i<<": "<<current->data<<endl; cout<<"Address node ke-"<<i<<": "<<current<<endl<<endl; current = current->link; i++; } } int main() { system("clear"); //generate address of the node node *head = (struct node *)malloc(sizeof (struct node)) ; //inserting data to the node
head->data = 45; node *middle = (struct node *)malloc(sizeof (struct node)) ; middle->data = 98; node *tail = (struct node *)malloc(sizeof (struct node)) ; tail->data = 75; //linking each node; head->link=middle; middle->link=tail; tail->link=NULL; cout<<"Berikut ini adalah urutan linked list"<<endl; printnode(head); deletemiddle(head); cout<<endl<<"Berikut ini adalah urutan linked list setelah elemen tengah dihapus : "<<endl; printnode(head); } Output : Penjelasan deletion no 3. void deletemiddle(node *head){ node *current=head->link; node *previous=head;
previous->link=current->link; delete(current); } •dibuat node baru yaitu current dan previous •node previous = node head, dan node current = head->link (node middle) •node previous dihubungkan ke current->link ( current->link itu sama saja dengan head->link->link , yaitu node tail). •Node previous(head) sekarang sudah terhubung ke node tail •Node current (middle) dihapus. 2. Visualisasi :