Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

LINKEDLIST

Status
Not open for further replies.

elise

Programmer
Joined
Sep 27, 2001
Messages
3
Location
AU
How do you write a method to print a LinkedList recursively, where by the method accepts a LinkedList and then passes the iterator to the recursive function for determining what is printed?
 
Hi elise,

To get an iterator for a Collection, you use the iterator method. You can then step through the objects in the Collection as required.

If the objects in the Linked List are Linked Lists, you can recursively pass them back to the method...


import java.util.LinkedList;
import java.util.Iterator;

...

public void recurseALinkedList(LinkedList list) {
Iterator iter = list.iterator();
while (iter.hasNext()) {
Object o = iter.next();
if (o instanceof LinkedList) {
recurseALinkedList((LinkedList) o);
} else {
// print the object
}
}
}



Hope this helps,
scrat
 
Status
Not open for further replies.

Similar threads

  • Locked
  • Question Question
Replies
7
Views
402
  • Locked
  • Question Question
Replies
9
Views
351

Part and Inventory Search

Sponsor

Back
Top