LeetCode 回文链表
234.回文链表
题目描述
给你一个单链表的头节点head
,请你判断该链表是否为。如果是,返回 true
;否则,返回 false
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
解题思路
首先,取指针的值用的也是→
本题的思路:首先利用快慢指针将链表一分为二,对第二段进行反转后,进行比较
(快慢指针:最后slow
指向的是第一段最后的元素)
需用到上到题的函数
代码
/*** 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) {//利用快慢指针将链表一分为二,最后slow指向第一段末尾ListNode* slow=head;ListNode* fast=head->next;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;}ListNode* tmp=head;slow=reverseList(slow->next);//将第二段链表进行反转,返回反转链表的头指针while(slow){if(tmp->val==slow->val){tmp=tmp->next;slow=slow->next;}else{return false;}}return true;}ListNode* reverseList(ListNode* head){ListNode* pre=NULL;ListNode* cur=head;while(cur){ListNode* tmp=cur->next;cur->next=pre;pre=cur;cur=tmp;}return pre;}
};