Palindrome Linked List(C++)

解题思路:

(1)现将链表存起来

(2)再使用夹逼定理,判断首尾是否依次相等

/**
 * 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> v;
        while(head) v.push_back(head->val),head=head->next;
        int left=0,right=v.size()-1;
        while(left<=right) {
	    if (v[left]!=v[right]) return false;
	    else left++,right--;
	}
	return true;
    }
};
发布了317 篇原创文章 · 获赞 279 · 访问量 43万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105700083