leetcode-----链表-----回文链表

请检查一个链表是否为回文链表。

进阶: 你能在 O(n) 的时间和 O(1) 的额外空间中做到吗?

/**
 * 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) {
		if(head==NULL||head->next==NULL)
            return true;
		vector<int> data;
		int cnt=0;
		
		while(head!=NULL){
			cnt++;
			data.push_back(head->val);
			head=head->next;
		}
		
		for(auto &i:data){
			if(i!=data[--cnt])
				return 0;
		}
		return 1;
    }
};

猜你喜欢

转载自blog.csdn.net/xuchen1230/article/details/80193440