— Diary, Programming — 1 min read
Wow, I've been inactive! Have put on some weight as well but motivated to start this again. It's a new month so let's go with Leetcode Question of the day. The question is to check whether the Linked List is a palindrome.
The first approach is to push everything in stack and then iterate over the list again to check if the reverse of the list matches with the original.
I've been rusty and I think the best way to reach that "follow up" to do it in O(n)
time and O(1)
space, is to first implement this approach and think what can be improved.
1bool isPalindrome(ListNode *head) {2 stack<int> s;3 ListNode *temp = head;45 while (temp) {6 s.push(temp->val);7 temp = temp->next;8 }910 while (head) {11 if (s.top() != head->val)12 return false;1314 s.pop();15 head = head->next;16 }1718 return true;19}
The above method has time and space complexity both as O(n)
.
The next approach is to reverse the 2nd half of the list, and the check if both the halves are equal (barring the middle element in a list with odd elements).
1ListNode *reverseList(ListNode *head) {2 ListNode *prev = NULL, *curr = head, *next = NULL;34 while (curr) {5 next = curr->next;6 curr->next = prev;7 prev = curr;8 curr = next;9 }1011 return prev;12}1314bool isPalindrome(ListNode *head) {15 ListNode *slow = head, *fast = head;16 ListNode *mid = NULL;1718 // return true if only one node19 if (head->next == NULL) return true;2021 while (fast && fast->next) {22 fast = fast->next->next;23 mid = slow;24 slow = slow->next;25 }2627 if (fast) slow = slow->next;2829 slow = reverseList(slow);3031 while (slow && head) {32 if (slow->val != head->val) return false;33 slow = slow->next;34 head = head->next;35 }3637 return true;38}
The complexity of this approach is O(n)
time and O(1)
space.