Simple c++ solution with comments

  • -1

    class Solution {
    bool isPalindrome(ListNode* head) {

      if(head == NULL) return true;           // If there is no tree return true
      vector<int> A;                          // Define a vector to store results
      while(head != NULL){
         A.push_back(head->val);             // Store all the linked list value into the vector A until it reaches to the end
         head = head->next;
      vector<int> B;                        // Make a copy of the linked list into another vector B
      B = A;
      reverse(A.begin(), A.end());         // Reverse the vector A, but B is still the original linked list
      return A == B;                      // Return true if they are same


  • 0

    Hint : space is supposed to O(1).

  • 0

    Of course my solution was O(n) space. Why don't we try to improve the solution with O(1) space with comments? It will be helpful for all of us!!!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.