Java: how to use dummy node or mark a node as dummy node
Asked Answered
C

1

8

A question asking you to delete the middle node in a linked list, only that node is give. The way to solve the problem is copy middle.next.element to middle.element and then delete middle.next by doing middle.next=middle.next.next

There's a special case which is when middle.next is the last node. The answer say that you could mark the middle node as dummy.

I'm not familiar with the idea "dummy". How to mark a node as dummy and how to use a dummy node in other cases?

What about dummy data in general?

Conjoined answered 2/1, 2014 at 16:48 Comment(3)
You can put some special value into the node or add an attribute (depends on the type of node). Then you have to analyze nodes be retrieving and to skip all nodes containing that special value or attribute (marked as dummy).Sunglasses
Would help if you could post (a link to) the original text/source. As I understand it, the idea is using a dummy node for the last element instead of just null, so if the second-to-last node (the last real node) is deleted, you do not have to backtrack to the node before that, to change that node's next element.Anemone
the idea is to avoid remove-operations on the list.Sunglasses
E
4

There is no general answer to this question. The implementation of the linked list must already define the concept of a dummy node and use it consistently. A typical way to achieve this would be by declaring a special dummy instance:

public class Node {
   public static final Object DUMMY = new Object();
   ...

and assigning middle.element = DUMMY;

As you can imagine, this will have no effect unless all the rest of the API implementation abides by this convention.

If your list is specified as unable to contain null elements, then you could also assign middle.element = null, but the rest of the story stays the same.

Epistrophe answered 2/1, 2014 at 16:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.