You are given with the singly linked list of say having characters, you have to tell whether the list is palindrome or not.
The list is palindrome when if you iterate the list from both the ends it should generate the same string. This problem can be solved in multiple ways. Some of the approaches are discussed here.
Approach 1: Brute force
The list is palindrome when if you iterate the list from both the ends it should generate the same string. This problem can be solved in multiple ways. Some of the approaches are discussed here.
Approach 1: Brute force
- Generate the string out of the list.
- Now check if the list is palindrome, by simple traversing the string from both the ends and comparing each character during traversal.
Approach 2: Reverse the list from middle
- Find out the mid element of the list by using two pointer ( slow will increment once, fast will increment twice).
- From the middle to the end reverse the list.
- Now use two pointers one pointing to the start of the list and other pointing to middle of the list.
- Then iterate list till middle ( from start) comparing each element from middle till end.
Approach 3: Use recursion
Advantage of this approach is we are using single pass for verifying if list is palindrome.
- Use the reference pointer variable.
- Use slow and fast pointers to reach till middle of the list using recursion.
- Now once we have reached to the middle of the list, assign the middle element to the reference pointer variable.
- Now while coming back from the recursion, compare at each step the element with the reference variable value.
- Point to the next node of reference variable and come out of recursion.
Advantage of this approach is we are using single pass for verifying if list is palindrome.
struct Node { char data; Node * pNext; }; bool IsListPalindrome(Node* head, Node* current, Node* & reverse) { if (head) { head = head->pNext; if (head) head = head->pNext; else { reverse = current->pNext; return true; } if (IsListPalindrome(head, current->pNext, reverse)) { if (current->data == reverse->data) { reverse = reverse->pNext; return true; } } return false; } reverse = current; return true; } |
No comments:
Post a Comment