Arista Networks Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
It is better move below code out of loop, so to reduce time cost.
if( curr == head )
{
head = head->next;
delete curr;
curr = head;
}
This is wrong because the head can change multiple times throughout the loop.
EX: if the linked list is 5->5->5->1
and you want to delete 5 it will not compute the correct result
bool DeleteNode(Linklist *p,int a)
{
static Linklist head=NULL;
if(head==NULL)
{
head=*p;
if(head->data==a)
{
if((*p)->next==NULL)
{
*p=NULL;
return 0;
}
*p=(*p)->next;
free(head);
head=NULL;
return DeleteNode(p,a);
}
}
if((*p)->next==0) return 0;
if(a!=(*p)->next->data)
{
return DeleteNode(&((*p)->next),a);
}
else
{
Linklist q=(*p)->next;
(*p)->next=q->next;
free((q));
if((*p)->next!=NULL)
{
return DeleteNode(&((*p)->next),a);
}
}
return 1;
}
void delete(Node **l, int target){
if(*l == null) return;
Node temp,nxt;
//setting the head node whose value is not equal to target
while(((*l) != null) && ((*l)->data == target) ){
temp = *l;
*l = (*l)->next;
free(temp);
}
if(*l == null) return;
temp = *l;
nxt = temp->next;
//iterate over rest of the nodes
while(nxt != null){
if(nxt->data == target){
temp->next = nxt->next;
nxt->next = null;
free(nxt);
nxt = temp->next;
}
else{
temp = nxt;
nxt = nxt->next;
}
}
}
void
delete_node(node_t **currp, int target)
{
node_t *tofree;
while (*currp) {
if ((*currp)->data == target) {
tofree = *currp;
*currp = (*currp)->next;
free(tofree);
} else {
currp = &(*currp)->next;
}
}
}
you are changing the head of the list when you delete an element in the middle of the list.
void del_node (node_t **l, int value)
{
node_t *prev = NULL;
node_t *cur = *l;
while (cur) {
if (cur->data == value) {
node_t *t = cur;
if (prev) {
/* Not list head */
prev->next = cur->next;
} else {
/* List head */
*l = cur->next;
}
cur = cur->next;
free(t);
} else {
prev = cur;
cur = cur->next;
}
}
}
void delete (Node **I, int target) {
Node *head=NULL;
Node *tmp=NULL;
Node *tail=NULL;
Node *next=NULL;
tmp = *I;
while (tmp) {
if (tmp->data == target) {
next = tmp->next;
free(tmp);
tmp = next;
next = NULL;
} else {
if (!head) {
head = tmp;
tail = tmp;
} else {
tail->next = tmp;
tail = tmp;
}
tmp = tmp->next;
}
}
if (!tail) {
tail->next = NULL;
}
*I = head;
return;
}
- thomas March 21, 2012