Linked List Implementation in Java

public class LinkedListImplementation {
    Node head; // create head object of class Node
    class Node{
        int data;
        Node next; // create next object of class Node
        
        Node(int d){
            this.data = d;
            this.next=null; // assign next to null for all new Node
        }
    }
    
    public void addFirst(int d){
        Node newNode = new Node(d);
        if(head ==null){
            head = newNode;
            return;
        }
        newNode.next= head;
        head = newNode;
        
    }
    
    public void addLast(int d){
        Node newNode = new Node(d);
        if(head ==null){
            head = newNode;
            return;
        }
        
        Node currentNode = head;
        while(currentNode.next !=null){
            currentNode = currentNode.next;
        }
        
        currentNode.next = newNode;
    }
    
    public void deleteFirst(){
        if(head == null){
              System.out.print("list is empty");
              return;
        }
        head = head.next;

    }
    
    public void deleteLast(){
          if(head == null){
              System.out.print("list is empty");
              return;
        }
        if(head.next == null){
             head=null;
              return;
        }
        Node secondLast = head;
        Node lastNode = head.next;
        
        while(lastNode.next !=null){
            lastNode = lastNode.next; 
            secondLast = secondLast.next;
        }
        secondLast.next =null;
    }
    
    
    public void printList(){
        Node currentNode = head;
        while(currentNode !=null){
            System.out.print(currentNode.data + "-->");
            currentNode = currentNode.next;
        }
    }
    
    public static void main(String[] args) {
        LinkedListImplementation list = new LinkedListImplementation();
        list.addLast(1);
        list.addLast(2);
        list.addLast(3);
        list.addFirst(5);
        
      //  list.deleteFirst();
      
        list.deleteLast();
        
        list.printList();
    }
}

Comments

Popular posts from this blog

What are sales territory in Netsuite?

How to get and set a sublist in netsuite suitlet suitescript 2.0

SuiteFoundation Exam Notes Netsuite Basics