Palindrome Linked List leetcode 234

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

判断给定的链表是不是回文的:

把要判断的链表分成两部分,将第二部分逆置,逐个与前一部分的val相比较,若不同返回false

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(!head||!head->next)return true;

        ListNode* slow=head;//这里定义slow,fast指针是为了寻找链表中间的位置
        ListNode* fast=head;
        while(fast->next&&fast->next->next){//假如链表有奇数个元素,则slow指针在循环后指向正中的元素;
        //若链表有偶数个元素,则循环后slow指向n/2的元素位置
            slow=slow->next;
            fast=fast->next->next;
        }
        slow->next=reverse(slow->next);//将链表后面部分逆置
        slow=slow->next;
        while(slow){
            if(head->val!=slow->val)return false;
            head=head->next;
            slow=slow->next;
        }
        return true;
    }
    ListNode* reverse(ListNode* head){
        if(!head||!head->next)return head;
        ListNode* pre=NULL;
        ListNode* next=NULL;
        while(head){
            next=head-next;
            head->next=pre;
            pre=head;
            head=next;
        }
    return pre;
    }
};

贴个递归解法

bool isPalindrome(ListNode* head) {
    if (!head || !head->next) return true;
    bool flag = true;
    recur_pal(head, head->next, flag);
    return flag;
}
void recur_pal(ListNode *&head, ListNode *tail, bool &flag) {
    if (head == tail || head == tail->next) return;
    if (tail->next) {
        recur_pal(head, tail->next, flag);
    }
    if (head->val != tail->val) { flag  = false; return;}
        head = head->next;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值