jn025
jn025

Reputation: 2895

Linked list remove method return removed node and new node

I'm using a linked list and I altered the standard remove method because I wanted to return both the removed node which is normal, but also return the node before it so for example if I wanted to change a direct reference i.e a tail node to the previous node I could. I was wondering if using a hashmap to achieve this as shown below is the best way to go about this or if there is a better way to achieve what I want? (Note: the below code works I'm just looking to see if there is a more elegant solution)

public HashMap<String, Node> remove(int i)
{
   if(isEmpty()) return null;
   else
   {
        HashMap<String, Node> temp  =   new HashMap<>();
        if(i == 0)
         {
             temp.put(REMOVE_NODE_KEY, firstNode);
             firstNode   =   (E)firstNode.getNext();
             temp.put(REMOVE_NEW_KEY, firstNode);
         }

         else
         {
             NodeIterator<E> iterator =   new NodeIterator<>(firstNode, i, 1);
             Node prev = iterator.getEnd();

             temp.put(REMOVE_NODE_KEY, prev.getNext());
             prev.setNext(prev.getNext().getNext());
             temp.put(REMOVE_NEW_KEY, prev);
         }

         size--;
         return temp;
   }
}

Upvotes: 2

Views: 216

Answers (2)

ajb
ajb

Reputation: 31689

A HashMap is rather heavy for this kind of usage. Really, all you want is some kind of "record" or "struct" with two elements. You could define a simple class:

public class NodeAndNewKey {
    public Node nodeKey;
    public Node newKey;
    public NodeAndNewKey(Node nodeKey, Node newKey) {
         this.nodeKey = nodeKey;
         this.newKey = newKey;
    }
}

public NodeAndNewKey remove(int i) { //etc.

You can probably come up with better names than I did.

Another possibility is to return a 2-element array:

public Node[] remove(int i) { // etc.

and define the [0] element as holding the "node key" and the [1] as holding the "new key", or whatever. I don't like it as much because it's less readable when you use it, but Android libraries do things like this sometimes. You could define constants like public static final int REMOVE_NODE_KEY = 0; public static final int REMOVE_NEW_KEY = 1; to make it more readable when retrieving elements from the result array.

Upvotes: 1

AndrewGrant
AndrewGrant

Reputation: 808

Couple you just return an array of Nodes?

temp = Node[2];
temp[0] = prev.getNext();
temp[1] = prev.getNext.getNext();
return temp;

Upvotes: 1

Related Questions