面试题 02.06 回文链表

1.普通版
把链表的每个值存储在数组中,然后从链表两端向中间挨个对比,如果有不等的,就返回false。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


bool isPalindrome(struct ListNode* head){
    //快慢指针?先找到中间位置,然后一个从中间开始,新建一个指针从头开始
    struct ListNode* fast=head;
    struct ListNode* slow=head;
    struct ListNode* begin=head;

    if(head==NULL)
    {
        return true;
    }

    //普通版
    int len=0;
    while(begin){
        begin=begin->next;
        len++;
    }
    int a[len];
    begin=head;
    for(int i=0;i<len;i++)
    {
        a[i]=begin->val;
        begin=begin->next;
    }
    for(int i=0, j=len-1;i<=j;i++,j--){
        if(a[i]!=a[j])
        {
            return false;
        }
    }
    return true;
}

2.进阶版,用o(1)的空间复杂度和o(n)的时间复杂度
直觉告诉我可以用快慢指针,可是我还是没想到怎么搞。
要反转链表,注意在最后一个whle中是判断p,而不是slow,因为slow最终会是NULL,所以一定会返回true。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


bool isPalindrome(struct ListNode* head){
    //快慢指针?先找到中间位置,反转链表,然后一个从中间开始,新建一个指针从头开始
    struct ListNode* fast=head;
    struct ListNode* slow=head;
    struct ListNode* begin=head;

    if(head==NULL)
    {
        return true;
    }

    //进阶版
    // 找到中间节点
    while(fast && fast->next){
        fast=fast->next->next;
        slow=slow->next;
    }
    // slow=slow->next;
    // 反转链表
    struct ListNode* p=NULL;
    struct ListNode* temp=NULL;
    while(slow)
    {
        temp=slow->next;
        slow->next=p;
        p=slow;
        slow=temp;
    }
    // 判断,是判断p而不是slow,因为slow最终会到NULL
    while(p)
    {
        if(begin->val != p->val)
        {
            return false;
        }
        begin=begin->next;
        p=p->next;
    }
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值