Google Interview Question: append an element to a double... | Glassdoor

Interview Question

Software Engineer Interview

append an element to a double linked list.

Answer

Interview Answer

1 Answer

0

//In java
public void addElement(Item item) {
       if (item == null) {
           throw new NullPointerException("Null item passed");
       } else {

       Node oldFirst = first;
       Node newNode = new Node();
       newNode.item = item;
       newNode.next = oldFirst;
       newNode.prev = null;
       first = newNode;

       if (first.next == null) {
           last = first;
       } else {
           oldFirst.prev = first;
       }
       oldFirst = null; //release the memory
       }
   }

paul odero on Apr 2, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.