L
L
Luke LikeSkywalker2019-06-01 11:41:57
Algorithms
Luke LikeSkywalker, 2019-06-01 11:41:57

Does anyone have a little cheat sheet on iterating over a linked list?

When should the while(list != null) and while(list.next != null) conditions be used ? In order to be confident in the condition at interviews.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BorLaze, 2019-06-01
@oolooq

When should the condition while(list != null) and while(list.next != null) be used?

See what you need. You can use either one or the other.
/* assuming there is list = list.next somewhere in the loop */
The while(list != null) condition means "move through the list until you get past the last element".
The condition while(list.next != null) means "move through the list until you reach the last element".
Accordingly, depending on the task, you must choose either one or the other. It is simply impossible to say unequivocally "do this, and not otherwise."

D
Denis Zagaevsky, 2019-06-01
@zagayevskiy

The interview should be held, thinking with your head, and not remembering some crazy patterns. The purpose of fucking you with these lists is not to find out that you remember patterns, but to see how you "twist" the code in your head.

R
res2001, 2019-06-01
@res2001

Usually
list.next == null means the current element (list) is the last one in the list
list == null - there is no list, possibly an error
Both options can be used in the same implementation in different situations.
In addition, there may be nuances and list.next == null in this particular implementation of the list is an error, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question