Quick actions

cmd+k|ctrl+k

Navigation

Languages

Basic data structure

Snippet info

Language

Java

Visibility

public

Author

pramodparthy

Created

2020-11-08T13:42:16Z

Updated

2020-11-10T01:22:12Z


class LinkedList{
    Node head;
    
    static class Node{
        int data;
        Node next;
        
        Node(int d){
            data=d;
            next=null;
        }
    }
    
    public static LinkedList insertAtEnd(LinkedList list,int d){
        Node newNode=new Node(d);
        if(list.head==null){
            list.head=newNode;
        }
        else{
            Node temp=list.head;
            while(temp.next!=null){
                temp=temp.next;
            }
            temp.next=newNode;
        }
        return list;
    }
    
    public static LinkedList deleteByKey(LinkedList list, int key){
        Node temp=list.head;
        Node prev=null;
        if(list.head.data==key)
            list.head=list.head.next;
        else{
            while(temp!=null && temp.data!=key){
                prev=temp;
                temp=temp.next;
            }
            prev.next=temp.next;
        }
        return list;
    }
    
    public static void printAll(LinkedList list){
        System.out.println("LinkedList: ");
        Node temp=list.head;
        while(temp!=null){
            System.out.print(temp.data+" ");
            temp=temp.next;
        }
    }
    
    
}

class LL {
    public static void main(String[] args) {
        LinkedList l=new LinkedList();
        l=LinkedList.insertAtEnd(l,5);
        l=LinkedList.insertAtEnd(l,4);
        l=LinkedList.insertAtEnd(l,3);
        l=LinkedList.insertAtEnd(l,2);
        LinkedList.printAll(l);
        l=LinkedList.deleteByKey(l,2);
        LinkedList.printAll(l);
    }
}
INFO