This was an interview question and I thought I'd share it with the rest of you.
How does one efficiently add to the tail of a linked list without using an "if"?
Remove the if from this function. (?
is still an if
).
typedef struct tNode_ tNode;
struct tNode_ {
tNode* pNext;
int data;
};
tNode* pHead = NULL;
tNode* pTail = NULL;
AddTail(tNode* pNode){
if(!pTail) {
pHead = pNode;
}
else {
pTail->pNext = pNode;
}
pTail = pNode;
pTail->pNext = NULL;
}