Friday 23 March 2018

Linked list dalam C++

#include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;
typedef struct TNode{
  int data;
  TNode *next;
 };
 TNode *head;

 void init(){
  head==NULL;
 }

 int isEmpty(){
  if(head==NULL)
   return 1;
   else
   return 0;
 }

 void insertdepan (int n){
  TNode *baru;
  baru = new TNode;
  baru->data=n;
  baru->next=NULL;
  if (isEmpty()==1){
   head=baru;
   head->next=NULL;
  }else{
   baru->next=head;
   head=baru;
  }
  cout<<"Data Terisi";
  }
 
 void insertbelakang(int n){
  TNode *baru, *bantu;
  baru = new TNode;
  baru->data=n;
  baru->next=NULL;
  if(isEmpty()==1){
   head=baru;
   head->next=NULL;
  }else{
   bantu=head;
   while(bantu->next!=NULL){
    bantu=bantu->next;
   }
   bantu->next=baru;
  }
  cout<<"Data Terisi";
 }

 void tampil(){
  TNode *bantu;
  bantu=head;
  if(isEmpty()==0){
   while(bantu!=NULL){
    cout<<bantu->data<<endl;
    bantu=bantu->next;
   }
  }else
  cout<<"Masih Kosong"<<endl;
 }

 void hapusdepan(){
  TNode *hapus;
  int d;
  if(isEmpty()==0){
   if(head!=NULL){
    hapus=head;
    d=hapus->data;
    head=hapus->next;
    delete hapus;
   }
   cout<<"Data : "<<d<<" Telah di Hapus"<<sendl;
  }
  else
  cout<<"Masih Kosong"<<endl;
 }

 main(){
  int pil;
  do{
   system("cls");
   int n;
   cout<<"1. Insert Depan"<<endl;
   cout<<"2. Insert Belakang"<<endl;
   cout<<"3. Display"<<endl;
   cout<<"4. Delete"<<endl;
   cout<<"5. Exit"<<endl;
   cout<<"Masukan Pilihan Anda :";pil=getche();
   switch(pil){
    case '1':{
     system("cls");
     cout<<"Masukan data :";cin>>n;
     isEmpty();
     insertdepan(n);
     break;
    }
    case '2':{
     system("cls");
     cout<<"Masukan Data :";cin>>n;
     isEmpty();
     insertbelakang(n);
     break;
    }
    case '3':{
     system("cls");
     isEmpty();
     tampil();
     break;
    }
    case '4':{
     system("cls");
     isEmpty();
     hapusdepan();
     break;
    }
   }getch();
  }while(pil!=5);
   return 0;
 }

0 comments:

Post a Comment