Advertisement
zoltanvi

Java linked list - unfinished

Jun 30th, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. public class Main {
  2.     public static void main(String[] args) {
  3.         LinkedList<String> list = new LinkedList<>();
  4.         list.add("First");
  5.         list.add("Second");
  6.         list.add("Third");
  7.         list.add("Fourth");
  8.         list.add("Fifth");
  9.         list.add("Sixth");
  10.  
  11.         list.printAll();
  12.  
  13.         list.delete(3);
  14.  
  15.         list.printAll();
  16.  
  17.     }
  18. }
  19.  
  20.  
  21. class LinkedList<T>{
  22.  
  23.     private Node head;
  24.     private Node tail;
  25.     private int size;
  26.  
  27.     private class Node{
  28.         public T data;
  29.         public Node next;
  30.  
  31.         public Node(T data){
  32.             this.data = data;
  33.         }
  34.     }
  35.  
  36.     public LinkedList(){
  37.         size = 0;
  38.     }
  39.  
  40.    
  41.     public void add(T data){
  42.         if(null == head){
  43.             head = new Node(data);
  44.             tail = head;
  45.         } else if(null == head.next) {
  46.             head.next = new Node(data);
  47.             tail = head.next;
  48.         } else{
  49.             tail.next = new Node(data);
  50.             tail = tail.next;
  51.         }
  52.         size++;
  53.     }
  54.  
  55.     // Semmilyen tail / size ellenorzes nincs megirva!
  56.     public void delete(int position){
  57.         if(position == 0){
  58.             Node tmp = head;
  59.             head = head.next;
  60.             tmp.next = null;
  61.  
  62.         } else{
  63.             Node n = head;
  64.             // Eljut a megelozo nodeig
  65.             for (int i = 0; i < position - 1; i++) {
  66.                 n = n.next;
  67.             }
  68.             Node tmp = n.next;
  69.             n.next = tmp.next;
  70.             tmp.next = null;
  71.         }
  72.  
  73.     }
  74.  
  75.  
  76.     public void printAll(){
  77.         Node n = head;
  78.         if(null != head){
  79.             System.out.print("\n" + n.data + " --> ");
  80.             while(null != n.next){
  81.                 n = n.next;
  82.                 System.out.print(n.data + " --> ");
  83.             }
  84.             System.out.print("null\n");
  85.         } else {
  86.             System.out.print("\nEmpty list!\n");
  87.         }
  88.     }
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement