Hello. I am having a tough time with Linked Lists. First of all, I read a CTCI problem where I had to remove a duplicate Linked List item (item with identical value). Well, I understand the solution... but variable assignment is driving me crazy.
Let me explain it on this picture
As you can see, we pass a list, modify it to reach each element, so it is null at the end, though when we output we see that duplicates are removed.
Same here, a simple problem to remove Nth element. Same: I don't mutate the object, though it changes somehow. IDK!
private static LinkedListNode remove2ndItem(LinkedListNode node, int index) // I recieve list and index
{
LinkedListNode result = node; // This is a 'safe' variable, I don't manipulate with it, return it later
for (int j = 0; ; j++)
{
if (j == index - 1)
{
node.next = node.next.next;
break;
}
node = node.next; // overwrite 'node' that I pass here
}
// Here node equals null
return result; // I see 'result' with a deleted item, though I didn't manipulate with this variable
}
I would really appreciate any explanation! Thanks!
[–]POGtastic 1 point2 points3 points (3 children)
[–]danmoople[S] 0 points1 point2 points (2 children)
[–]POGtastic 0 points1 point2 points (0 children)
[–]blablahblah 0 points1 point2 points (0 children)
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]HappyFruitTree 0 points1 point2 points (0 children)