LinkedList All operations JAVA !!


 

package Linkedlist;


public class linkedlist1 {
Node head;
class Node{
int data;
Node next;

Node(int data){//constructor
this.data=data;
this.next=null;
}
}
//add first
public void addfirst(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
return;
}
newNode.next=head;
head=newNode;
}
//addlast
public void addLast(int data){
Node newNode=new Node(data);
if(head==null){
head=newNode;
return;
}
Node currNode=head;
while (currNode.next!=null){
currNode=currNode.next;
}
currNode.next=newNode;

}
//print the linkedlist
public void printList(){
if(head==null){
System.out.println("list is empty ");
return;
}
Node currNode=head;
while (currNode!=null){
System.out.print(currNode.data+" - ");
currNode=currNode.next;
}
System.out.println("null");
}

//delete operations
//delete first
public void delfirst(){
if(head==null){
System.out.println("the list is empty");
return;
}
head=head.next;
}
//delete last element from the linked list

public void dellast(){
if(head==null){
System.out.println("the 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 static void main(String[] args) {
linkedlist1 list=new linkedlist1();
// list.addfirst(78);
//// list.addfirst("a");
list.addLast(90);
list.addLast(91);
list.addLast(92);
list.printList();
list.delfirst();
list.dellast();
list.printList();

}
}

Comments

Popular Posts