Linked list program in java using scanner
Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).
All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Example 1: Add element to LinkedList using Scanner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.LinkedList; import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); LinkedList<String> languages = new LinkedList<>(); for(int i=0;i<5;i++){ languages.add(scan.next()); } System.out.println("LinkedList: " + languages); } } |
Output:
1 2 3 4 5 6 7 8 |
C# Python Java SQL C++ LinkedList: [C#, Python, Java, SQL, C++] |
Example 2: Find element index using scanner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.LinkedList; import java.util.Scanner; class Main { public static void main(String[] args) { LinkedList<String> languages = new LinkedList<>(); Scanner scan = new Scanner(System.in); // add elements in LinkedList languages.add("Python"); languages.add("C++"); languages.add("Java"); languages.add("C#"); String element =scan.next(); System.out.println("Element Index: " + languages.indexOf(element)); } } |
Output:
1 2 3 4 |
C++ Element Index: 1 |
Example 3: Remove elements Using the remove() Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.LinkedList; import java.util.Scanner; import java.util.function.Predicate; public class Main { public static void main(String[] args) { LinkedList<String> languages = new LinkedList<>(); Scanner scan = new Scanner(System.in); // add elements in LinkedList languages.add("Python"); languages.add("C++"); languages.add("Java"); languages.add("C#"); System.out.println("Enter a language"); String element =scan.next(); languages.remove(element); System.out.println("Updated LinkedList: " + languages); } } |
Output:
1 2 3 4 5 |
Enter a language Java Updated LinkedList: [Python, C++, C#] |