题目链接
题目描述
示例
示例1:
输入: 1->2 输出: false
思路
思路1:数组+双指针
思路2:迭代
使用快慢指针将链表平分,将后半部分反转,再判断是否是回文。
注:最好不要修改原链表的结构,若修改,再返回前再修改回来。
题解
思路1:数组+双指针
/*** 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;while (head) {vec.emplace_back(head->val);head = head->next;}int left = 0, right = vec.size() - 1;while (left < right) {if (vec[left] != vec[right]) {return false;}++left;--right;}return true;}};
思路2:迭代
/*** 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 {private:ListNode* splitList(ListNode* head) {ListNode* fast = head;ListNode* slow = head;while (fast->next != nullptr && fast->next->next != nullptr) {fast = fast->next->next;slow = slow->next;}return slow;}ListNode* reverseList(ListNode* head) {ListNode* prev = nullptr;ListNode* curr = head;ListNode* next = nullptr;while (curr) {next = curr->next;curr->next = prev;prev = curr;curr = next;}return prev;}public:bool isPalindrome(ListNode* head) {if (head == nullptr) {return true;}ListNode* firstPartTail = splitList(head);ListNode* secondPartHead = reverseList(firstPartTail->next);ListNode* p1 = head;ListNode* p2 = secondPartHead;bool ret = true;while (p2) {if (p1->val != p2->val) {ret = false;break;}p1 = p1->next;p2 = p2->next;}firstPartTail->next = reverseList(secondPartHead);return ret;}};
