I am relatively new to python and am trying to understand how to relate Python with C/C++. Consider the problem: Check if a given Linked List is a Palindrome. From this source, I found a very effective solution:
// Initial parameters to this function are &head and head
bool isPalindromeUtil(struct node **left, struct node *right)
{
/* stop recursion when right becomes NULL */
if (right == NULL)
return true;
/* If sub-list is not palindrome then no need to
check for current left and right, return false */
bool isp = isPalindromeUtil(left, right->next);
if (isp == false)
return false;
/* Check values at current left and right */
bool isp1 = (right->data == (*left)->data);
/* Move left to next node */
*left = (*left)->next;
return isp1;
}
// A wrapper over isPalindromeUtil()
bool isPalindrome(struct node *head)
{
isPalindromeUtil(&head, head);
}
Basically a pointer to pointer is assigned to the front (left pointer) and a pointer is assigned to the end of the list (right pointer). Once the pointers reach their respective positions, they recurse through and find match the values. Here, *left maintains the state of the pointer to pointer whose value persists through the recursive loop. One of the solutions in python would be passing the left pointer back along with the boolean value. However if there are multiple pointer to pointers being used, the number of return elements explode! Bad design. Is there any other way of doing it?
EDIT:
Thank you so much for the responses! I forgot to mention that I'm not trying to solve the Palindrome problem here. I am trying to understand if there is a Pythonic equivalent way of working with pointers. What I am trying to comprehend is when if a question is posed to me, which uses data structures such as linked list, should I try to convert it into other data structures such as list or if I need to be creative and solve the question using the same data structure. Since pointer to pointer is pretty important concept in Linked List and BST, is there an equivalent solution or work around for this concept?
Edit #2: The rough code I have come up with is as below. However, the left_ptr remains stuck in the same position since its a pointer and not pointer to pointer:
def palindrome_utils(self, left_ptr, right_ptr):
if right_ptr is None:
return True
prev_result = self.palindrome_utils(left_ptr, right_ptr.get_link())
cur_result = left_ptr.get_data() == right_ptr.get_data()
left_ptr = left_ptr.get_link()
return cur_result and prev_result
def palindrome(self):
return self.palindrome_utils(self.head, self.head)