
Sumityadav
How to get the first and last occurrence of the specified elements in a linked list in Java?
Hello all, I am new to learning Java Programming and want to learn java from scratch. I was writing a Java program to get the first and last occurrence of the specified elements in a linked list. Here is the Code:
import java.util.LinkedList;
import java.util.Iterator;
public class program {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
list.add("Red");
ist.add("Green");
list.add("Black");
list.add("Pink");
list.add("orange");
// print original list
System.out.println("Original linked list:" + list);
// Find first element of the List
Object first_element = list.getFirst();
System.out.println("First Element is: "+first_element);
// Find last element of the List
Object last_element = list.getLast();
System.out.println("Last Element is: "+ element);
}
}
When I was trying to run the code I shows and error, I do not understand how to solve this. can any one please help in in this?
Marked As Solved

faust
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.
Popular Backend topics










Other popular topics









Latest in Backend
Latest (all)
Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /js
- /rails
- /python
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /haskell
- /emacs
- /svelte
- /onivim
- /typescript
- /crystal
- /c-plus-plus
- /tailwind
- /kotlin
- /gleam
- /react
- /flutter
- /elm
- /ocaml
- /vscode
- /opensuse
- /centos
- /ash
- /php
- /deepseek
- /scala
- /zig
- /html
- /debian
- /nixos
- /lisp
- /agda
- /sublime-text
- /textmate
- /react-native
- /kubuntu
- /arch-linux
- /ubuntu
- /revery
- /manjaro
- /django
- /spring
- /diversity
- /lua
- /nodejs
- /c
- /julia
- /slackware
- /neovim