Berikut ini merupakan program linkedlist dengan java untuk menambah data mahasiswa di depan dan dibelakang, serta dapat menghapus data mahasiswa didepan maupun dibelakang. Dan dapat menampilkan hasilnya setelah selesai dimodifikasi.
source code:
package mk_asd;
class Node{
public String data1;
public int data2;
import
java.util.Scanner;
public Node next;
public Node(String nama, int nim){
data1 = nama;
data2 = nim;
}
}
public class
SingleLinkedList {
static String nama;
static int nim;
private static Node pointer;
public SingleLinkedList() {
pointer = null;
}
public void
buatNode(String nama, int nim) {
Node
nodeBaru = new Node(nama, nim);
nodeBaru.data1 = nama;
nodeBaru.data2 = nim;
nodeBaru.next = pointer;
pointer = nodeBaru;
}
public void addDepan(String nama, int nim)
{
Node depan = new Node (nama, nim);
depan.next = pointer;
pointer = depan;
}
public void addBelakang (String nama, int
nim) {
Node prev = null;
Node cur = pointer;
Node belakang = new Node(nama, nim);
belakang.data1 = nama;
belakang.data2 = nim;
belakang.next = null;
while (cur!=null){
prev = cur;
cur = cur.next;
}
prev.next = belakang;
}
public Node hapusDiDepan(){
Node HDepan = pointer;
pointer = pointer.next;
return HDepan;
}
public void hapusDiBelakang (){
Node Hapus;
Hapus = pointer;
Node last = new Node(nama, nim);
while(Hapus.next.next!=null){
Hapus = Hapus.next;
}
last = Hapus.next;
Hapus.next = null;
}
public void cetak(String kom){
System.out.println(kom);
Node n = pointer;
while(n!=null){
System.out.println(n.data2+"\t"+n.data1);
n = n.next;
}
System.out.println();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner (System.in);
SingleLinkedList l = new
SingleLinkedList();
System.out.println("--Masukkan
Data Awal--");
System.out.print("Masukkan Nama :
");
String nama = in.nextLine();
System.out.print("Masukkan NIM :
");
int nim = in.nextInt();
l.buatNode(nama,nim);
do {
System.out.println("\n-----> Menu <-----");
System.out.println("1.
Tambahkan di Depan");
System.out.println("2.
Tambahkan di Belakang");
System.out.println("3. Hapus
di Depan");
System.out.println("4. Hapus
di Belakang");
System.out.println("5.
Tampilkan");
System.out.println("6.
Keluar");
System.out.println();
System.out.print("Tentukan
Pilihan Anda : ");
switch(in.nextInt()){
No comments:
Post a Comment