Thursday, October 4, 2012

Struktur Data: Single Linked List Non Circular (Final Version) Example

/*
@author: Didik Kurniawan
**** Ilmu Komputer FMIPA Universitas Lampung *****
*/
#include <iostream>
  #include <stdlib.h>
  #include <string.h>
  using namespace std;
  struct produk {
  int kode;
  char nama_produk[100];
  produk *next;
  };
  produk *head;
void awal(){
  head=NULL;
  }
bool isEmpty(){
  if (head==NULL)
  return true;
  return false;
  }
  void tambahDataDepan(int kode, char nama_produk[100]){
  produk *baru;
  baru= (produk*) malloc (sizeof(produk));
  baru->kode=kode;
  strcpy(baru->nama_produk,nama_produk);
  baru->next=NULL;
  if (isEmpty()){
  head=baru;
  } else {
  baru->next=head;
  head=baru;
  }
  }
  void tambahDataBelakang(int kode, char nama_produk[100]){
  produk *baru;
  produk *bantu;
  baru= (produk*) malloc (sizeof(produk));
  baru->kode=kode;
  strcpy(baru->nama_produk,nama_produk);
  baru->next=NULL;
 if (isEmpty()){
  head=baru;
  } else {
  bantu=head;
  while(bantu->next!=NULL){
  bantu=bantu->next;
  }
  bantu->next=baru;
  }
}
  void hapusDepan(){
  if (!isEmpty()){
  produk *hapus;
  hapus=head;
  if (head->next!=NULL){
  head=head->next;
  delete hapus;
  } else {
  head=NULL;
  }
  } else {
  cout<<"Data masih kosong";
  }
  }
  void hapusBelakang(){
  if (!isEmpty()){
  produk *hapus;
  if (head->next!=NULL){
  produk *bantu;
  while(bantu->next->next!=NULL){
  bantu=bantu->next;
  }
  hapus=bantu->next;
  bantu->next=NULL;
  delete hapus;
  } else {
  head=NULL;
  }
  } else {
  cout<<"Data masih kosong";
  }
  }
void cetak(){
  if (!isEmpty()){
  produk *bantu;
  bantu=head;
  while(bantu!=NULL){
  cout<<bantu->kode<<"\t"<<bantu->nama_produk<<"\n";
  bantu=bantu->next;
  }
  } else{
  cout<<"Data masih kosong";
  }
  }
  int main(){
  awal();
 tambahDataDepan(1,"Netbook Asus eeepc 1215");
  tambahDataBelakang(2,"Netbook Asus eeepc 1210");
  tambahDataDepan(3,"Netbook Asus eeepc 1010");
  tambahDataBelakang(4,"Printer Canon Pixma MP 258");
  hapusBelakang();
  hapusDepan();
  cetak();
  return 0;
  }