1public class LinkedList {
2
3 private Node head;
4 private int length = 0;
5
6 public LinkedList() {
7 this.head = new Node(null);
8 }
9
10 public int size() {
11 return length;
12 }
13
14
15 // Adds an element to the end of the list
16 public void add(Object data) {
17
18 Node node = new Node(data);
19 Node iterator = head;
20 while (iterator.getNext() != null){
21 iterator = iterator.getNext();
22 }
23 iterator.setNext(node);
24 length++;
25 }
26
27
28 // Obtains an element by index
29 public Object get(int index) {
30
31 if (head.getNext() == null || index >= length){
32 return null;
33 }
34
35 Node iterator = head.getNext();
36 int counter = 0;
37
38 while(counter < index){
39
40 iterator = iterator.getNext();
41 counter++;
42 }
43 return iterator.getData();
44
45 }
46
47
48 // Returns the index of the element in the list
49 public int indexOf(Object data) {
50 Node obj=head;
51 for (int i = 0; i < length; i++) {
52 obj = obj.getNext();
53 if (obj.getData().equals(data)) {
54 return i;
55 }
56 }
57 return -1;
58 //throw new Exception("Data not found");
59 }
60
61
62 // Removes an element from the list
63 public boolean remove(Object data) {
64
65 if (head.getNext() == null){
66 return false;
67 }
68
69 Node iterator = head;
70
71 while(iterator.getNext() != null){
72
73 if (iterator.getNext().getData().equals(data)){
74 iterator.setNext(iterator.getNext().getNext());
75 length--;
76 return true;
77 }
78
79 iterator = iterator.getNext();
80 }
81
82 return false;
83 }
84
85 private class Node {
86
87 private Object data;
88 private Node next;
89
90 public Node(Object data) {
91 this.data = data;
92 next = null;
93 }
94
95 public Object getData() {
96 return data;
97 }
98
99 public void setData(Object data) {
100 this.data = data;
101 }
102
103 public Node getNext() {
104 return next;
105 }
106
107 public void setNext(Node next) {
108 this.next = next;
109 }
110 }
111
112}
1// Java program to iterate the elements
2// in an LinkedList
3
4import java.util.*;
5
6public class GFG {
7
8 public static void main(String args[])
9 {
10 LinkedList<String> ll
11 = new LinkedList<>();
12
13 ll.add("Geeks");
14 ll.add("Geeks");
15 ll.add(1, "For");
16
17 // Using the Get method and the
18 // for loop
19 for (int i = 0; i < ll.size(); i++) {
20
21 System.out.print(ll.get(i) + " ");
22 }
23
24 System.out.println();
25
26 // Using the for each loop
27 for (String str : ll)
28 System.out.print(str + " ");
29 }
30}