Program Linked List Dengan Struct

Contoh program linkedlist  :

#include<iostream>
using namespace std;

struct mahasiswa{
    int nim;
    string nama;
    float  ipk;
    mahasiswa *next;
};

//mahasiswa *head=NULL;
//mahasiswa *tail=NULL;

void baru(mahasiswa *&head, mahasiswa *&tail){
head = NULL;
tail = NULL;
}

bool isEmpty(mahasiswa *&head){
if( head == NULL){return true;}
else {return false;}
}

void push(mahasiswa *&head, mahasiswa *&tail){
    mahasiswa *mawar = new mahasiswa;
    cin>>mawar->nim >> mawar->nama >> mawar->ipk;          
    mawar->next = head;
    if(head==NULL)
    {
        tail= mawar;
    }
  head = mawar;          
}

void show(mahasiswa *&head){
mahasiswa *p = head;
while( p != NULL){
cout<< p->nim << endl;
cout<< p->nama << endl;
cout<< p->ipk << endl << endl;

p = p->next;
}
}

void pop(mahasiswa *&head, mahasiswa *&tail){
mahasiswa *out = NULL;
if(isEmpty(head)) {
cout<<"Tidak ada data"<<endl;}
else if( head==tail) {
out = head;
baru(head,tail);//head=NULL; tail = NULL
cout<<out->nim<<endl<<out->nama<<endl<<out->ipk<<endl;
}
else {
out = head;
head = head->next;
cout<<out->nim<<endl<<out->nama<<endl<<out->ipk<<endl;
}
}
int main(){
    int pil;
    mahasiswa *head=NULL;
    mahasiswa *tail=NULL;
  do{
    cout<<"LINKED LIST (STACK di head)"<<endl;
    cout<<"1. New"<<endl;
    cout<<"2. Push"<<endl;
    cout<<"3. Pop"<<endl;
    cout<<"4. Show"<<endl;
    cout<<"0. Exit"<<endl;
    cout<<"Masukan pilihan :"<<endl;
    cin>>pil;
if(pil == 1){ baru(head, tail); }
else if( pil == 2 ) { push(head, tail); }
else if( pil == 3 ) { pop(head, tail); }
else if( pil == 4 ) { show(head); }
  }while(pil != 0);
 //system("pause");
 return 0;
}


Hasil output :


Previous
Next Post »