Advertisement
saban123

Untitled

Dec 28th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.16 KB | None | 0 0
  1. class Node{
  2.     int data;
  3.     Node next;
  4.     Node(int a){
  5.         data = a;
  6.     }
  7. }
  8. class LinkedListWorking {
  9.     Node kepala;
  10.     int c;
  11.     void create(int b){
  12.         kepala = new Node(b);
  13.     }
  14.     void add(int b){
  15.         Node current = kepala;
  16.         if (kepala == null)
  17.             create(b);
  18.         else{
  19.             while(current.next != null){
  20.        
  21.                 current = current.next;
  22.             }
  23.             current.next = new Node(b);
  24.         }
  25.     }
  26.     void find(int b){
  27.         Node current = kepala;
  28.         int n = 0;
  29.         if (current == null)
  30.             System.out.println(“Data kosong”);
  31.         else{
  32.             while(current.next != null){
  33.                 if (current.data == b){
  34.                     System.out.println(“Indeks:+n);
  35.                     return;
  36.                 }
  37.                 n++;
  38.                 current = current.next;
  39.             }
  40.            
  41.                 System.out.println(“Tidak ditemukan”);
  42.         }    
  43.     }  
  44.     void addIndex(int index, int b){
  45.         Node current = kepala;
  46.         Node after = current.next;
  47.         for (int n = 1;n<(index-1);n++){
  48.             current = current.next;
  49.             after = after.next;
  50.         }
  51.         Node newnode = new Node(b);
  52.        
  53.         current.next = newnode;
  54.         current.next.next = after;
  55.     }
  56.    public void display(){
  57.         Node current = kepala;
  58.         if (current == null)
  59.             System.out.println(“Data kosong”);
  60.         else{
  61.             while(current.next != null){
  62.                 System.out.print(current.data+” “);
  63.                 current = current.next;
  64.             }System.out.println(current.data+” “);
  65.         }
  66.     }
  67.  public static void main(String[] args) {
  68.        LinkedListWorking a = new LinkedListWorking();      
  69.         a.add(2);
  70.         a.add(3);
  71.         a.add(7);
  72.         a.add(5);
  73.         a.add(1);
  74.         a.add(6);
  75.         a.add(9);
  76.       a.display();
  77.     System.out.println(“mencari nilai 3 terletak pada”);
  78.         a.find(3);
  79.     System.out.println(“menyisipkan nilai 9 pada indeks ke-2);
  80.         a.addIndex(3,9);
  81.       a.display();
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement