Leetcode刷题(234. 回文链表)

一.题目

请判断一个链表是否为回文链表

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

二.代码(C)

方法一

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
int length(struct ListNode* head);
void cutout(struct ListNode* head,int i);
bool find(struct ListNode* head,int i);
bool isPalindrome(struct ListNode* head)
{
    int count;
    count = length(head);
    if (count==0 || count==1)
        return true;
    int i;
    if (count%2)
    {
        i=count/2;
        cutout(head,i);
    }  
    for(i=count/2;i>0;i--)
    {
        if (find(head,i))
        {
            continue;
        }
        else
            return false;
    }
    return true;
}
bool find(struct ListNode* head,int i)
{
    struct ListNode* head1=NULL;
    while(i-1)
    {
        head1 = head;
        head = head->next;
        i--;
    }
    if (head->val==head->next->val)
    {
        if (head->next->next!=NULL)
            head1->next=head->next->next;
        return true;
    }
    else
        return false;
   
}
void cutout(struct ListNode* head,int i)
{
    while(i-1)
    {
        head = head->next;
        i--;
    }
    head->next = head->next->next;
}
int length(struct ListNode* head)
{
    int count=0;
    while(head)
    {
        count++;
        head = head->next;
    }
    return count;
}

方法二

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool isPalindrome(struct ListNode* head)
{
    struct ListNode* slow=head,*fast=head;
    struct ListNode* temp=NULL,*temp2;
    if(!head ||!head->next)
        return true;
    do
    {
        if(!fast->next)
        {
            fast = slow->next;
            slow = temp;
            temp = NULL;
        }
        else if (!fast->next->next)
        {
            fast = slow->next;
            slow->next = temp;
            temp = NULL;
        }
        else
        {
            fast = fast->next->next;
            temp2 = slow->next;
            slow->next = temp;
            temp = slow;
            slow = temp2;
        }
    }while(temp!=NULL);
    while(fast)
    {
        if (fast->val!=slow->val)
            return false;
        fast = fast->next;
        slow = slow->next;
    }
    return true;
}

三.提交记录

方法一

在这里插入图片描述
在这里插入图片描述

方法二

在这里插入图片描述
在这里插入图片描述

四.备注

方法一:先找到中间位置,逐次前后对比是否等值。
方法二:快慢指针,其中慢指针移动过程中将链表反转,最后对比两个链表的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值