2018.5.20(判断回文数)

判断回文数

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
using namespace std;

struct List
{
    int data;
    List *next;
};

List *Insert(List *head,int num)
{
    List *p,*tail_start,*tail_end;

    p=(List*)malloc(sizeof(List));
    p->data=num;
    p->next=NULL;

    if(head==NULL)
        return p;

    tail_end=head;
    while(tail_end!=NULL)
    {
        tail_start=tail_end;
        tail_end=tail_end->next;
    }
    tail_end=p;
    tail_start->next=tail_end;

    return head;
}

List *Create(int *num,int len)
{
    List *head=NULL;
    for(int i=1;i<=len;i++)
        head=Insert(head,num[i]);
    return head;
}

bool Judge_01(List *head)
{
    stack<int >cnt;
    for(List *p=head;p!=NULL;p=p->next)//根据栈“先进后出”的性质,将链表中的数据存储到栈中
        cnt.push(p->data);

    List *p=head;

    while(!cnt.empty())//如果栈为空,返回true,否则返回false;
    {
        if(cnt.top()!=p->data)//如果不相等,则返回false;
            return false;
        cnt.pop();
        p=p->next;
    }
    return true;
}
bool Judge_02(int num[],int len)
{
    int p1=1,p2=len;
    while(p1<=p2)
        if(num[p1++]!=num[p2--])
            return false;

    return true;
}

int main()
{
    int N;
    while(cin>>N)
    {
        List *head;
        int num[N+1];

        for(int i=1;i<=N;i++)
            cin>>num[i];

        head=Create(num,N);

        printf("********************\n");
        printf("%p\n",head);//使用指针p遍历链表,head指向的地址不变;
        List *p=head;
        do
        {
            printf("%d ",p->data);
            p=p->next->next;//p指向当前位置的下下个地址;
        }while(p!=NULL&&p->next!=NULL);
        if(N&1)
           printf("%d",p->data);
        printf("\n");
        printf("%p\n",head);
        printf("*********************\n");

        int judge_01=Judge_01(head);//使用辅助空间判断;
        int judge_02=Judge_02(num,N);//不使用辅助空间

        string ans_01=(judge_01)?"YES":"NO";
        string ans_02=(judge_02)?"YES":"NO";

        cout<<ans_01<<endl;
        cout<<ans_02<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/violet_ljp/article/details/80381319