In: Computer Science
can u give me an example of how to removing Double Linked List a node at a given location in java
the method should be like this:
public void removeFromLocation(int location) {
}
}
Source Program:
public void removeFromLocation(int location)
{
Node temp=head;
int i=0,count=0;
while(temp.next!=null)
{
count++;
temp=temp.next;
}
System.out.println("number of nodes:"+(count+1));
temp=head;
if(location <=(count+1))
{
if(location==1)
{
temp=temp.next;
head=temp;
}
else if(location==(count+1))
{
while(temp.next!=null)
{
temp=temp.next;
}
temp=temp.previous;
temp.next=null;
}
else
{
i=1;
while(i<location)
{
temp=temp.next;
i++;
}
temp=temp.previous;
temp.next=temp.next.next;
}
}
sample output:
Complete Program:
public class DoublyLinkedList {
class Node
{
int data;
Node previous;
Node next;
public Node(int data)
{
this.data = data;
}
}
Node head, tail = null;
public void addNode(int data)
{
Node newNode = new Node(data);
if(head == null)
{
head = tail = newNode;
head.previous = null;
tail.next = null;
}
else
{
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
tail.next = null;
}
}
public void removeFromLocation(int location)
{
Node temp=head;
int i=0,count=0;
while(temp.next!=null)
{
count++;
temp=temp.next;
}
System.out.println("number of nodes:"+(count+1));
temp=head;
if(location <=(count+1))
{
if(location==1)
{
temp=temp.next;
head=temp;
}
else if(location==(count+1))
{
while(temp.next!=null)
{
temp=temp.next;
}
temp=temp.previous;
temp.next=null;
}
else
{
i=1;
while(i<location)
{
temp=temp.next;
i++;
}
temp=temp.previous;
temp.next=temp.next.next;
}
}
}
public void display()
{
Node current = head;
if(head == null)
{
System.out.println("List is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while(current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args)
{
DoublyLinkedList dList = new DoublyLinkedList();
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
dList.display();
dList.removeFromLocation(3);
dList.display();
}
}