C++快慢指针法判断回文串

简要概述快慢指针法(单向链表):
设置两个指针,初始值均为头节点。
快指针为一次前进两个节点。慢指针为一次前进一个节点。快指针走到头的时候慢指针应该恰好到中点位置,慢指针在前进过程中顺便将链表反向链接。快指针走到头之后,慢指针走到中点,此时慢指针继续向前走,而慢指针建立的反向链表则掉头往回走,此时判断两个链表是否值相等。
该算法时间复杂度为O(n)
在这里插入图片描述
当快指针走到为空(回文串为偶数个字符),或者其next为空(奇数个字符,此时要将慢指针再向前走一步才能与反向链表进行比较)。
在这里插入图片描述
文章末尾附上C++实现代码。
现在点出几个易错点:

  • 在上述判断快节点是否走到头的while循环中,我将&&的判断条件写反了,先判断next是否为null,后判断节点是否为null,此时如果节点已经为null,其next就会不知道跑到哪里去了,由于c++可以访问合理的内存,所以会导致程序死循环或者直接报错(看编译器设置)。
  • 总之C/C++的指针必须使用得十分谨慎,稍不留神就会出错,之前写python写多了,对指针null的问题不太敏感了。

代码:

#include <iostream>
#include <stdio.h>
using namespace std;

struct node
{
    char data;
    node* next;
};

bool isHuiwen(node* nod)
{
    if(nod->next==NULL)
        return true;
    node* nod2=nod;
    node* nod1=nod;
    node* f=NULL;
    node* guodu=NULL;
    while(nod2!=NULL&&nod2->next!=NULL)
    {
        nod2=nod2->next->next;
        node* f=nod1->next;
        nod1->next=guodu;
        guodu=nod1;
        nod1=f;
    }
    if(nod2!=NULL)
    {
        nod1=nod1->next;
    }
    while(nod1!=NULL)
    {
        if(nod1->data!=guodu->data)
            return false;
        else
        {
            nod1=nod1->next;
            guodu=guodu->next;
        }
    }
    return true;
}

int main()
{
    char ch;
    ch=getchar();
    node* guodu1=NULL;
    node* head=NULL;
    while(ch!='\n')
    {
        node* newnode=new node;
        newnode->data=ch;
        newnode->next=NULL;
        if(!guodu1)
        {
            guodu1=newnode;
            head=newnode;
        }
        else
        {
            guodu1->next=newnode;
            guodu1=newnode;
        }
        ch=getchar();
    }

    bool flag=isHuiwen(head);
    if(flag)
    {
        cout<<"Yes";
    }
    else
    {
    cout<<"No";
    }
}
发布了48 篇原创文章 · 获赞 23 · 访问量 1308

猜你喜欢

转载自blog.csdn.net/qq_37724465/article/details/104295271