JAVA - loop a linkedlist/ find a string in linkedlist
high, how do i开发者_运维问答 loop through a linked list. i need to write a method find(), that returns true if a certain string is in the list
public boolean find( Stack<String> s, String key )
{
for( String item : s )
{
if( item.equals( key ) )
return true;
}
return false;
}
Typically, you have a pointer to the head of the list. You check for whether the pointed-to item matches your search string. If it does, you return true. If not, you move your pointer to the next item in the list. If you reach the end of the list, you return false.
(I'm assuming this is homework, so I won't actually write the code. If you show us some non-working code, we'll help you make it work.)
Edited to add: If you're working with a linked list, why are you passing in a stack? Anyway, the code you've posted looks like it should work. You should probably post the code you're using to set up the data and call the find
method; there may be a problem there.
The error you mention sounds like maybe you aren't passing a Stack correctly; you should be able to do a foreach loop on the contents of a Stack.
There's already a "contains" method:
http://download.oracle.com/javase/6/docs/api/java/util/LinkedList.html#contains(java.lang.Object)
If your LinkedList elements are only Strings, it should work OK. Otherwise you'll need to override the 'equals' method of your model.
It sounds like you're saying that you're implementing a custom linked list implementation called Stack
, and you're having looping over your list using for-each syntax. In order to use that syntax, your class needs to implements the Iterable
interface. This means you will need to create an Iterator
for your list as well, which will provide next()
, hasNext()
, and remove()
methods
精彩评论