【数据结构】链表的回文结构

  • 题目描述

对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

测试样例:

1->2->2->1

返回:true
  • 思路分析:

先遍历一遍链表,计算出节点的个数,再从头开始走,走到链表的中间位置,然后把链表的中间位置作为要逆置的头结点,最后再把逆置后的节点与头结点到中间位置之前的节点进行比较,如果相等,则就是回文结构,否则就不是回文结构。

  • 具体代码如下:
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
ListNode*   reverseList(ListNode* phead)
    {
        struct ListNode* newhead=NULL;
        struct ListNode* cur=phead;
        while(cur)
        {
            struct ListNode* next=cur->next;
            cur->next=newhead;
            newhead=cur;
            cur=next;
        }
        return newhead;
     }
    bool chkPalindrome(ListNode* A) {
        int n=0;
        struct ListNode* cur=A;
        while(cur)//判断链表的个数
        {
            cur=cur->next;
            n++;
        }
        cur=A;
        int mid=n/2;
        while(mid--)//链表从头开始走到中间位置
        {
            cur=cur->next;
        }
        struct ListNode* head1=A;
        struct ListNode* head2=reverseList(cur);
        mid=n/2;
        while(mid--)
        {
            if(head1->val==head2->val)
            {
                if(head1&&head2)
              head1=head1->next;
              head2=head2->next;
            }
            else
            {
               return false;
            }
        }
    return true;
    }
};

其实这道题有一个漏洞,它题目要求链表长度小于等于900,那如果用数组来判断的话,也是可以的,甚至比使用链表更简单

  • 具体实现代码如下:
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        int a[900];
        int n=0;
        struct ListNode* cur=A;
        while(cur)
        {
          a[n]=cur->val;
           cur=cur->next;
            n++;
        }
        int left=0;
        int right=n-1;
        while(left<right)
        {
            if(a[left]!=a[right])
            {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值