276.LeetCode | 234. 回文链表
Posted 每天一个开发小知识
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了276.LeetCode | 234. 回文链表相关的知识,希望对你有一定的参考价值。
每天一个开发小知识
01
请判断一个链表是否为回文链表
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: 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) {
vector<int> vec;
ListNode * p = head;
while (NULL != p)
{
vec.push_back(p->val);
p = p->next;
}
for (int i = 0; i < vec.size() / 2; ++i)
{
if (vec[i] != vec[vec.size() - 1 - i])
{
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) {
if (NULL == head || NULL == head->next)
{
return true;
}
ListNode * fast = head;
ListNode * slow = head;
while (NULL != fast->next && NULL != fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
fast = head;
slow = reverseList(slow->next);
while (NULL != slow)
{
if (fast->val != slow->val)
{
return false;
}
fast = fast->next;
slow = slow->next;
}
return true;
}
ListNode* reverseList(ListNode* head) {
ListNode * pre = NULL;
ListNode * curr = head;
while (NULL != curr)
{
ListNode * next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
return pre;
}
};
以上是关于276.LeetCode | 234. 回文链表的主要内容,如果未能解决你的问题,请参考以下文章