234. Palindrome Linked List (Easy)

1.問題

  • 判斷linked list是否屬於迴文

2.想法

3.程式碼

/**
 * 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) {
        string str;
        ListNode *list = head;
        while(list) {
            str.push_back(list->val);
            list = list->next;
        }
        for (int i = 0; i < str.size(); i++) {
            if (str[i] != str[str.size() - 1 - i]){
                return false;
            }
        }
        return true;
    }
};

4.Performance

Last updated