Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
How to modify elements in Java's Linked List in constant time while iterating through it?

I'm trying to iterate through Java's implementation of a linked list and modify each element of the linked list in constant time. I'm aware of the set() method of linked list but that operation is O(n). So if I used the set() method in a loop it would be O(n^2) which isn't what I want. Since I'm iterating through the linked list, I already know the position of the node of which I want to modify it's contents. Is there a way for me to do this in constant time using Java's Linked List?

I've done this many times with custom implementations but I don't see a way to do this in constant time. I tried iterating below but I'm missing something.

LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator iterator = list.iterator();

while (iterator.hasNext()) {
    iterator.remove();
    iterator.set(); // using set() wouldn't be O(1)
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Iterator does not have a set method. Fortunately, you're working with a LinkedList, and ListIterator does have a set method.

ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
  it.set("new_" + it.next());
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!