回文链表
题目链接:回文链表
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
方法一:额外数组
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> vals;
while (head != nullptr) {
vals.emplace_back(head->val);
head = head->next;
}
for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {
if (vals[i] != vals[j]) {
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 {
ListNode* findmid(ListNode* head) {
ListNode* slow = head,*fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reserve(ListNode* head) {
ListNode* ans = nullptr;
ListNode* cur = head;
while(cur) {
ListNode* t = cur->next;
cur->next = ans;
ans = cur;
cur = t;
}
return ans;
}
public:
bool isPalindrome(ListNode* head) {
ListNode* head1 = findmid(head);
ListNode* head2 = reserve(head1);
while (head2) {
if (head->val != head2->val) {
return false;
}
head = head->next;
head2 = head2->next;
}
return true;
}
};