给定一个链表的 头节点 head ,请判断其是否为回文链表。
如果一个链表是回文,那么链表节点序列从前往后看和从后往前看是相同的。
示例 1:
输入: head = [1,2,3,3,2,1]
输出: true
示例 2:
输入: head = [1,2]
输出: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/aMhZSa
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> data;
while(head) {
data.emplace_back(head->val);
head = head->next;
}
for(int i = 0; i < data.size()/2; i++) {
if(data[i] != data[data.size()-i-1])
return false;
}
return true;
}
};
只想到了第一种害
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
stack<int> data;
ListNode*p = head;
if(!head)
return true;
while(p) {
data.push(p->val);
p = p->next;
}
while(head) {
if(head->val != data.top())
return false;
data.pop();
head = head->next;
}
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next)
return true;
stack<int> data;
ListNode* slow = head->next, *fast = head;
while(fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
while(slow) {
data.push(slow->val);
slow = slow->next;
}
while(data.size()) {
if(head->val != data.top())
return false;
data.pop();
head = head->next;
}
return true;
}
};
快慢指针搞了好久,悲伤