Algorithm and Data Structure

Removing an Item from the List

Rate this Entry
by , 02-19-2012 at 07:52 AM (471 Views)
For removal of an item out of List, different methods would be discussed here. Use these methods.

• remove()
• removeFirst()
• removeLast()

Java Code: This is the code to explain removal of an element from the List
```theList.removeLast();
theList.remove(0);
theList.removeFirst();
theList.removeFirst();

import java.util.*;
public class TestLinkedList
{
public static void main(String[] args)
{
int pause;
String temp;
LinkedList theList = new LinkedList();
theList.add("1");
theList.add(0, "2");
theList.addFirst("3");
theList.addLast("4");
System.out.println("Size: "+theList.size());
System.out.println("Element 0: "+theList.get(0));
temp = theList.get(1);
System.out.println("Element 1: "+temp);
System.out.println("Size :"+ theList.size());
System.out.println("First :"+ theList.getFirst());
System.out.println("Last :"+ theList.getLast());
System.out.println("Size yet again: "+theList.size());
theList.removeFirst();
System.out.println("Size yet again: "+theList.size());
theList.removeLast();
theList.remove(0);
theList.removeFirst();
System.out.println("Empty Size: "+theList.size());
for(int x=0; x<100; x++) {
theList.add(""+x);
}
System.out.println("Loop Size :"+ theList.size());
for(int x=100; x>0; x--) {
theList.removeLast();
}
System.out.println("Empty Size: "+theList.size());
}
}```

Tags:
Categories
Linked List