1
while(element != null)
{
    //temp = element (useless)
    element = element.node;

    //can't do (element.node).method();
    //neither temp.method();
}

To traverse a LinkedList we do the above. However, what if I want to go back to an earlier node? Is that even possible? I thought about storing the node in a temp variable, but I wouldn't be able to changes the nodes in the LinkedList since the temporary variable would only store the value of the node and not the object.

I didn't expect LinkedList to be so difficult to work with, because I was used to working with non-dynamic data structures (array).

4

2 回答 2

0

There is a related data-structure called a "Doubly linked list", in which in addition to storing a pointer to the next element, you ALSO store a pointer to the previous element. This way you can not only go down the list, but also back up. Will this serve your purpose?

Also, to respond to your suggestion of using a temporary variable, I think that will in fact work as long as the data you are storing is an object (instead of a primitive), and the changes you need to make are changes to the object rather than reassignment of the object.

于 2013-03-30T23:03:28.137 回答
0

Doubly linked list, as Jimmy Lee mentions above, is the classic approach. You could also save references to "interesting" nodes. Or you could create a new linked list with the links going in the opposite direction as you traverse the list. And finally, one trick is to simply reverse the links as you traverse the list, but this change the original list.

于 2013-03-30T23:06:28.790 回答