LeetCode 234 The road to LeetCode of palindrome linked list HERODING

Please judge whether a linked list is a palindrome linked list.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Advanced:
Can you solve this problem with O(n) time complexity and O(1) space complexity?

Problem solving idea: I
did a recent linked list problem and found that the double pointer method is a unique weapon to solve this type of problem. Here, the data in the linked list is first stored in the container, and then the double pointer starts from the head and the other starts from the tail. If they are different, return false until the double pointers meet. The code is as follows:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool isPalindrome(ListNode* head) {
    
    
        vector<int> res;
        while(head != NULL){
    
    
            res.push_back(head -> val);
            head = head -> next;
        }
        for(int i = 0, j = res.size() - 1; i < j; i ++, j --){
    
    
            if(res[i] != res[j]){
    
    
                return false;
            }
        }
        return true;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109240345