In: Computer Science
method to remove all elements frrom my linked list (java)
Node class
package com;
public class Node {
Node next;
int data;
Node(int data){
this.data=data;
}
}
LinkedList class having all implementation
package com;
public class LinkedListWithBasicOp {
Node head; //head
public void addAtHead(int value){
Node temp=head;
if(head==null){ //if head is null make new new node
head=new Node(value);
}
else{
Node n=new Node(value); //add new node to first
head=n;
n.next=temp;
}
}
public void deleteAtIndex(int index){
Node temp=head;
Node prev=head;
int i=0;
if(index==0){ //if index is 0 make delete node at first
temp=head.next;
head=temp;
temp=null;
}
else{
while(temp!=null){ //Traverse through list
if(i==index){ //if i==index
prev.next=temp.next; //delete node at position i
}
i++;
prev=temp;
temp=temp.next;
}
}
}
public void removeAllNode(){
while(head!=null){
deleteAtIndex(0);
}
}
public void print(){ //print linked list
Node t=head;
if(t==null){
System.out.println("List is empty");
return;
}
while(t!=null){
System.out.print(t.data+"->");
t=t.next;
}
System.out.println("Null");
System.out.println(" ");
}
}
//driver program to test
package com;
public class Tester {
public static void main(String[] args) {
LinkedListWithBasicOp m=new LinkedListWithBasicOp();
m.addAtHead(4);
m.addAtHead(5);
m.addAtHead(3);
m.addAtHead(2);
m.print();
m.removeAllNode();
m.print();
}
}
output
2->3->5->4->Null
List is empty