Untitled
unknown
c_cpp
a year ago
3.9 kB
10
Indexable
#include <iostream> using namespace std; struct Node { int age; string name; Node *next; }; Node *head; Node *tail; void init() { head = NULL; tail = NULL; } bool isEmpty() { if (head == NULL) return true; else return false; } void insertDepan(string name, int nilai) { // Buat Node baru Node *baru = new Node; baru->name = name; baru->age = nilai; baru->next = NULL; if (isEmpty() == true) { head = tail = baru; tail->next = NULL; } else { baru->next = head; head = baru; } } // Hitung Jumlah List int hitungList() { Node *hitung; hitung = head; int jumlah = 0; while (hitung != NULL) { jumlah++; hitung = hitung->next; } return jumlah; } // Tambah Tengah void insertTengah(string name, int age, int posisi) { if (posisi < 1 || posisi > hitungList()) { cout << "Posisi diluar jangkauan" << endl; } else if (posisi == 1) { cout << "Posisi bukan posisi tengah" << endl; } else { Node *baru, *bantu; baru = new Node(); baru->name = name; baru->age = age; // tranversing bantu = head; int nomor = 1; while (nomor < posisi - 1) { bantu = bantu->next; nomor++; } baru->next = bantu->next; bantu->next = baru; } } // Hapus Tengah void hapusTengah(int posisi) { Node *hapus, *bantu, *bantu2; if (posisi < 1 || posisi > hitungList()) { cout << "Posisi di luar jangkauan" << endl; } else if (posisi == 1) { cout << "Posisi bukan posisi tengah" << endl; } else { int nomor = 1; bantu = head; while (nomor <= posisi) { if (nomor == posisi - 1) { bantu2 = bantu; } if (nomor == posisi) { hapus = bantu; } bantu = bantu->next; nomor++; } bantu2->next = bantu; delete hapus; } } // Ubah Tengah void ubahTengah(string name, int age, int posisi) { Node *bantu; if (isEmpty() == false) { if (posisi < 1 || posisi > hitungList()) { cout << "Posisi di luar jangkauan" << endl; } else if (posisi == 1) { cout << "Posisi bukan posisi tengah" << endl; } else { bantu = head; int nomor = 1; while (nomor < posisi) { bantu = bantu->next; nomor++; } bantu->name = name; bantu->age = age; } } else { cout << "List masih kosong!" << endl; } } // Tampilkan List void tampil() { Node *bantu; bantu = head; if (isEmpty() == false) { while (bantu != NULL) { cout << bantu->name << "\t" << ends; cout << bantu->age << endl; bantu = bantu->next; } cout << endl; } else { cout << "List masih kosong!" << endl; } } int main() { init(); int arr = 7; int age; string name; for (int i = 0; i < arr; i++) { cout << "Masukkan Nama ke- " << i+1 << ": " ; cin >> name; cout << "Masukkan Umur ke- " << i+1 << ": " ; cin >> age; cout << ("\n"); insertDepan(name, age); } cout << ("\n"); // Hapus data akechi hapusTengah(5); insertTengah("Futaba", 18, 2); insertDepan("Igor", 20); ubahTengah("Reyn", 18, 5); tampil(); return 0; }
Editor is loading...
Leave a Comment