How to get the first and last occurrence of the specified elements in a linked list in Java?

There are a few typing errors in your code, for example " ist.add(“Green”);" instead of “list.add(“Green”);”

And System.out.println("Last Element is: "+ element); should be System.out.println("Last Element is: "+ last_element);

with these changes your code shall run correctly.

Besides, it’s important to note that in Java we use cammelCase instead of snake_case, you should use firstElement and lastElement instead of first_element and last_element, this won’t affect the code but is the common pattern used by the vast majority of the Java Developers, so it’s better to follow it too.

4 Likes