Microsoft Interview Question
SDETsTeam: Cloud
Country: United States
void RemoveHead (node * head)
{
if(head == Null) return;
node * newHead = head - > next;
free(head);
head = newHead;
}
void RemoveHead (node * head)
{
node * newHead = head - > next;
free(head);
head = newHead;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
struct list_node{
int data;
struct list_node * next;
};
typedef struct list_node node;
void add_node( node ** head, int add_data ){
if( *head == NULL ){
*head = (node *)malloc(sizeof(node));
(*head)->data = add_data;
(*head)->next = NULL;
}
else{
node *t = (node *)malloc(sizeof(node));
t->data = add_data;
t->next = (*head);
(*head) = t;
}
}
void print_list( node ** head ){
node * p = *head;
while( p != NULL){
cout << p->data << endl;
p = p->next;
}
}
void del_head( node ** head ){
if( *head == NULL ){
cout << "operation invalid" << endl;
}
else{
node * t = (*head)->next;
free(*head);
(*head) = t;
}
}
int main(){
node * head;
add_node( &head, 4 );
add_node( &head, 5 );
del_head( &head );
print_list( &head );
return 0;
}
void RemoveHead (node ** head)
{
mutex_lock(&_head_mutex);
if(head == null || *head == null)
return;
node *h = (*head)->next;
free(*head);
(*head) = h;
mutex_unlock(&_head_mutex);
}
This is an excellent interview question. Anyone fails to answer this question should not be hired. A very fundamental question between pionter and pointer to pointer. Pointer to pointer should be used anywhere potentially can modify where the pointer points to. In this case "free" is to change where the pointer points to, from a valid address to null after free.
Any function in linked list that can call malloc/free should use pointer to pointer. Please refer to this blog about more common APIs.
cpluspluslearning-petert.blogspot.co.uk/2014/08/data-structure-and-algorithm-linked.html?m=1
void delet(struct node**p)
- satyajit January 24, 2015{
struct node*temp=*p;
*p=(*p)->next;
free(temp);
}