How to remove first and last element from LinkedList

package JavaLinkedListExample;

import java.util.LinkedList;
import java.util.Scanner;

/*
 * Here we will learn to remove first and last element from LinkedList
 */
public class RemoveFirstAndLastElement {

	public static void main(String[] args) {

	    /**
	     * Constructs a new Scanner that produces values scanned
	     * from the specified input stream.(Used to take input from user)
	     */
		Scanner scanner = new Scanner(System.in);

		LinkedList<String> linkedList = new LinkedList<String>();
		String objInput;

		System.out.println("Insert the elements in List(Enter exit to quit)");
		objInput = scanner.next();

		/*
		 * equalsIgnoreCase method compares this String to another String,
		 * ignoring case considerations.
		 */
		while (!objInput.equalsIgnoreCase("exit")) {
			linkedList.add(objInput);
			objInput = scanner.next();
		}
		System.out.println("nElements in List");
		for(Object obj:linkedList)
			System.out.println(obj);
		System.out.println("nSize of the list:"+linkedList.size());
	   /**
	     * Removes and returns the first element from this list.
	     */
		System.out.println("Removing the first element :"+linkedList.removeFirst());

	    /**
	     * Removes and returns the last element from this list.
	     */
		System.out.println("Removing the last element :"+linkedList.removeLast());

		System.out.println("nElements in List after removing First and Last Element");
		for(Object obj:linkedList)
			System.out.println(obj);
		System.out.println("nSize of the list now:"+linkedList.size());		

	}
}

 

By | 2012-09-25T03:20:37+00:00 September 25th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment