21 Şubat 2020 Cuma

LinkedList Exercises






public class FirstLastelementLList {
        Node head;     
        static class Node{
           int data;
           Node next;

           Node(int d){
           this.data = d;
           next = null;
           }
    }     

       static Node lastElement(Node nodes){      

        Node currNode = nodes;     

        while(currNode.next != null){

             currNode = currNode.next;

        }
        return currNode;     

        }     
       static Node firstelement(Node nodes){
           Node head = nodes;
           return head;
       }    

       static Node addFirst(Node nodes, int d){
           Node head = nodes;
           Node newNode = new Node(d);
           newNode.next = head;
           return newNode;    
       }
       static Node addToEnd(Node nodes, int d){
           Node currNode = nodes;
           Node newNode = new Node(d);
           while(currNode.next != null){
                   currNode = currNode.next;
           }
           currNode.next = newNode;
           return nodes;
           }    

       static void printList(Node nodes){
           Node currNode = nodes;
           while(currNode.next != null){
                System.out.println(currNode.data);
                currNode = currNode.next;
         }
         System.out.println(currNode.data);
          }     

       static int findIndex(Node nodes, int d){
           int counter = 1;
           Node currNode = nodes;
           while(currNode.next != null){
               if(currNode.data == d){
                   return counter;
               }
               counter++;
               currNode = currNode.next;
           }
           return counter;
           }      

       static Node addDataToGivenIndex(Node nodes, int d, int index){
           int counter = 0;
           Node currNode = nodes;
           Node newNode = new Node(d);      
           while(currNode.next != null){
                    if((counter+1) != index){
                    counter ++;
                   currNode = currNode.next;
                  }else if((counter+1) == index){
               Node nextNode = currNode.next;
               currNode.next = newNode;
               newNode.next = nextNode;
               break;

               }
       }
       return nodes;
       }
        public static void main(String[] args) {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);

        n1.next = n2;

        n2.next = n3;

        System.out.println("First element is :" + firstelement(n1).data);

        System.out.println("Last element is :" +lastElement(n1).data);

        n1 = addFirst(n1, 0);

        printList(n1);

        n1 = addToEnd(n1, 4);

        printList(n1);

        System.out.println("Index of 3 is :" + findIndex(n1, 3));

        n1 = addDataToGivenIndex(n1, 5, 3);

        printList(n1);

        }
}

Hiç yorum yok:

Yorum Gönder