Monday, December 9, 2013

[Amazon Interview]: Append and delete node in unordered DLL

Append and delete a node in an unordered DLL.

2 comments:

  1. // A utility function to remove a node 'temp' fromt DLL. Note that the
    // function may change head and tail pointers, that is why pointers to
    // these pointers are passed.
    void removeNode(struct node **head_ref, struct node **tail_ref,
    struct node *temp)
    {
    if (*head_ref == NULL)
    return;

    if (*head_ref == temp)
    *head_ref = (*head_ref)->next;
    if (*tail_ref == temp)
    *tail_ref = (*tail_ref)->prev;
    if (temp->next != NULL)
    temp->next->prev = temp->prev;
    if (temp->prev != NULL)
    temp->prev->next = temp->next;

    delete(temp);
    }

    ReplyDelete
  2. void appendNode(struct node **head_ref, struct node **tail_ref, char x)
    {
    struct node *temp = new node;
    temp->a = x;
    temp->prev = temp->next = NULL;

    if (*head_ref == NULL)
    {
    *head_ref = *tail_ref = temp;
    return;
    }
    (*tail_ref)->next = temp;
    temp->prev = *tail_ref;
    *tail_ref = temp;
    }

    ReplyDelete