I would appreciate feedback on the linked list implementation and usage below for question 2.6 from Cracking the coding interview book.
struct Node {
char value;
shared_ptr<Node> next;
Node(char v) : value(v) {};
};
shared_ptr<Node> head;
void createSampleList(string str)
{
auto ptr = head;
for (const char ch : str)
{
if(!head) {
head = make_shared<Node>(ch);
ptr = head;
}
else {
ptr->next = make_shared<Node>(ch);
ptr = ptr->next;
}
}
}
bool isPalindrome() {
auto slow = head;
auto fast = head;
stack<char> tempStack;
while (fast != nullptr && fast->next != nullptr)
{
tempStack.push(slow->value);
slow = slow->next;
fast = fast->next->next;
}
if(fast != nullptr)
slow = slow->next;
while (slow != nullptr)
{
char reverseVal = tempStack.top();
tempStack.pop();
if(reverseVal != slow->value)
return false;
slow = slow->next;
}
return true;
}
char
, unless you have a very good reason.int
should be the numeric type you use by default, since it's the default for both your system and the language itself. – Cody Gray 2 days ago