将每一个节点存入vector中,然后按链表的长度由最长到1判断是否为回文链表,如果初始链表为回文的,则返回空链表,否则返回最长的回文子链表的头节点,将回文子链表的最后一个节点的指向置为nullptr。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* maxPalindrome(ListNode* head) {
// write code here
ListNode* current = head;
vector<ListNode*> list;
while(current != nullptr) {
list.push_back(current);
current = current->next;
}
for(int i = list.size(); i > 0; i--) {
for(int j = 0; j < list.size() - i + 1; j++) {
if(isPalindrome(list, j, j + i - 1)) {
if(i == list.size()) {
return nullptr;
}
list[j + i - 1]->next = nullptr;
return list[j];
};
}
}
return nullptr;
}
bool isPalindrome(vector<ListNode*> list, int start, int end) {
while(start <= end) {
if(list[start]->val != list[end]->val) {
return false;
}
start++;
end--;
}
return true;
}
};



京公网安备 11010502036488号