Elegant solutions to common interview problems - Part 1 - Linked Lists
Define a linked list node for integers
class Node {
public:
int data;
Node* next;
};
Reverse a singly linked list in-place iteratively
Node* reverseIterative(Node* head) {
// Initialize two pointers, current(ptr) and previous
Node* ptr = head;
Node* prev = NULL;
// At each node, we point it's next to previous
while (ptr) {
Node* next = ptr->next;
ptr->next = prev;
// Advance both pointers
prev = ptr;
ptr = next;
}
// Point head to last node
head = prev;
return head;
}
Reverse a singly linked list in-place recursively
Node* reverseRecursive(Node* head) {
if (!head || !head->next) {
return head;
}
Node* rest = reverseRecursive(head->next);
// Point head's next node towards head
head->next->next = head;
head->next = NULL;
return rest;
}
Traverse a linked list recursively
void traverse(Node* head) {
if (!head) {
return;
} else {
cout<<head->data<<endl;
}
traverse(head->next);
}
Traverse a linked list recursively in reverse order
void traverseReverse(Node* head) {
if (!head) {
return;
}
traverseReverse(head->next);
cout<<head->data<<endl;
}
Print nth element of linked list (counted from 1)
void printNthElement(Node* head, int n) {
if (!head) {
return;
}
if (n == 1) {
cout<<head->data;
}
printNthElement(head->next, n-1);
}
Print nth element from last in linked list
void printNthLastElement(Node* head, int* n) {
if (!head) {
return;
}
printNthLastElement(head->next, n);
*n = *n - 1;
if (*n == 0) {
cout<<head->data;
return;
}
}
computer-science
]