How to add element in LinkedList

package JavaLinkedListExample;

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

/*
 * Here we will learn to add element in Linked List in the beginning and in the End
 */
public class AddElements {
	public static void main(String args[]) {

		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the first element to add in list");
		Object firstElement = scanner.nextLine();
		System.out.println("Delimiter "+ scanner.delimiter());

		System.out.println("Enter the last element to add in list");
		Object lastElement = scanner.nextLine();

		LinkedList list = new LinkedList();

		System.out.println("Enter the item to add in list(Enter exit when done)");
		String elementToAdd = scanner.nextLine();

		while(!elementToAdd.equalsIgnoreCase("exit"))
		{
			list.add(elementToAdd);
			elementToAdd = scanner.nextLine();
		}
		/*
		 * addFirst() method inserts the specified element at the beginning of
		 * given list.
		 */
		list.addFirst(firstElement);

		// Here we are adding 2 element @ first position so last item added
		// @first position will be considered.
		//list.addFirst(3);

		/*
		 * addLast(E e) appends the specified element to the end of given list.
		 */
		list.addLast(lastElement);

		System.out.println("Elements in Listn");
		for (Object i : list) {
			System.out.println(i);
		}
	}
}

 

Leave A Comment

Your email address will not be published. Required fields are marked *