How to Navigate LinkedList in both direction(forward/reverse)

package JavaLinkedListExample;

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

/*
 * Here we will learn to navigate LinkedList in Both direction(Back and forth)
 *
 * Note*: Iterator can be used to navigate only one direction while ListIterator can be used to
 *        navigate in any direction(Back and forth).
 */
public class NavigateLinkedListInBothDirection {

	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 when done)");
		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("Insert the points from where you want to start navigate(Only Integer)");

		int index = scanner.nextInt();
		ListIterator listIterator = linkedList.listIterator(index);

		System.out
				.println("Which element you want to see(Enter exit when done)n1: Previousn2: Next");

		String navigateOption = scanner.next();
		while (!navigateOption.equalsIgnoreCase("exit")) {

			if (navigateOption.equals("1")) {
				/**
				 * Returns true if this list iterator has more elements when
				 * traversing the list in the reverse direction.
				 */
				if (listIterator.hasPrevious()) {
					System.out.println("Previous Element :"
							+ listIterator.previous());
					System.out.println("Previous Index :"
							+ listIterator.previousIndex());
				} else
					System.out.println("There is no Previous Element");

			} else if (navigateOption.equals("2")) {
				/**
				 * Returns true if this list iterator has more elements when
				 * traversing the list in the forward direction.
				 */
				if (listIterator.hasNext()) {
					/**
					 * Returns the next element in the list.
					 */
					System.out.println("Next Element :" + listIterator.next());

					/**
					 * Returns the previous element in the list.
					 */
					System.out.println("Next Index :"
							+ listIterator.nextIndex());
				} else
					System.out.println("There is no Next Element");
			} else
				System.out.println("Not a valid option");

			navigateOption = scanner.next();
		}

	}
}

 

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

About the Author:

Leave A Comment