Browsing the archives for the Pointers tag

Nth-to-Last Element in a Singly Linked List

Question: Devise an algorithm to determine the Nth-to-Last element in a singly linked list of unknown length. If N = 0, then your algorithm must return the last element. Answer: Given that the only way to traverse a singly linked list is forwards from the head, it is not possible to just count N elements […]

Singly Linked List – Delete Node

Question: You are given a pointer to a node (not the tail node) in a singly linked list. Delete that node from the linked list. Write code in C. Answer: To delete a node, you have to redirect the next pointer of the previous node to point to the next node instead of the current one. Since […]

Reverse a Linked-List

Question: Reverse a Linked-list. Write code in C. Answer: There are multiple ways to go about this. Let’s first look at a recursive solution. Node * reverse( Node * ptr , Node * previous) { Node * temp; if(ptr->next == NULL) { ptr->next = previous; return ptr; } else { temp = reverse(ptr->next, ptr); ptr->next […]

Loop in a Singly-Linked List

Question: How would you find a loop in a singly-linked list? Answer: This is a very typical tech interview question that has a very elegant solution that runs in O(n) time and O(1) space. Also referred to as the “Tortoise and Hare Algorithm”,  the solution uses a fast pointer (traversing the list two items at […]

Little Endian or Big Endian?

Question: Is your machine little or big endian? Answer: Let first take a look at the solution before we discuss about it. int isLittleEndian( void ) { unsigned int temp = 0x12345678; char * tempAddress = &temp; if( *tempAddress == 0x12 ) { return 0; // Indicating False } else { return 1; // Indicating […]


Reverse the Order of Words in a String

Question: Reverse the order of words in a string in C using as little additional memory as possible. Answer: The solution for this questions uses the solution of Reverse a String. I am going to make a small change to that solution by adding a length parameter. It will probably be better for you to […]

Reverse a String

Question: Reverse a string in C using as little additional memory as possible. Answer: The first solution needs the size of a char and size of two integers, all of which will be allocated from the stack. This solution is the most commonly accepted “good” solution. Here is the code. void reverseString(char* str) { int i, […]