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?

2 Likes

Corresponding tweet for this thread:

Share link for this tweet.

1 Like

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