# 判定是否为回文数(本人数据结构初学者,初次尝试完整的写一个算法，逻辑感觉不清晰望大家指教)

0

//试写一个算法判定是否为回文序列

#include<stdio.h>
#include<stdlib.h>
int main(){
# define stacksize 100
typedef char datatype;
typedef struct
{
datatype data[stacksize];
int top;
}seqstack;
int i; seqstack * s,p;char x;
int m;
int a [10];
int length = (sizeof(a)/sizeof(a[0]));
s=(seqstack*)malloc(sizeof (seqstack));

if(s->top==stacksize-1){
return 1;

}else{

printf("栈已满");

}

for (i=0;i<length;i++){
scanf("%d",&a[i]);
}

if(length%2==0){

for(i=0;i<length;i++){

s->data[++s->top]=a[i];
}

m =length/2+1;

x=s->data[s->top];

if( x==a[m]){

while(i=2;i<=length/2+2;i++){

int n =length/2+i;
s->top--;

if(s->data[s->top]==a[n]){
printf("是回文数");
}else{

printf("不是回文数");

}

}
}else{
printf("不是回文数");

}

}else{
for(i=0;i<(length-1)/2;i++){

s->data[++s->top]=a[i];
}

m =length-1;

x=s->data[s->top];

if(x==a[m]){

while(i=2;i<=(length-1)/2+2;i++){

int n =(length-1)/2+i;
s->top--;

if(s->data[s->top]==a[n]){
printf("是回文数");
}else{

printf("不是回文数");

}

}

}

}

}

0

```/*

1->2->2->1

*/

#include <iostream>
using namespace std;

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

//链表结点构造
ListNode*  create_list_node(int val)
{
ListNode* pNode = new ListNode(val);
return pNode;
}
//链表结点连接
void connect_list_node(ListNode* pCur, ListNode* pNext)
{
pCur->next = pNext;
}

class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
ListNode* pSlow = A;
ListNode* pFast = A;

while(pFast != NULL && pFast->next != NULL)
{
pSlow = pSlow->next;
pFast = pFast->next->next;
}
//反转链表后半部分指针
ListNode* prev = pSlow;//临时保存用
pSlow = pSlow->next;
prev->next = NULL;//最中间的点的next置为NULL
while(pSlow != NULL)
{
cout<<pSlow->val<<endl;
ListNode* tmp = pSlow->next;//保存后面的结点
pSlow->next=prev;
prev = pSlow;
pSlow = tmp;
}

ListNode* pForward = A;//指向头结点
ListNode* pBackward= prev;//指向链表最后一个结点

while(!(pForward == pBackward || pForward->next == pBackward))
{
if(pForward->val != pBackward->val)
return false;
pForward = pForward->next;
pBackward = pBackward->next;
}
return true;
}
};

void test()
{
//创建结点
ListNode* pNode1 = create_list_node(1);
ListNode* pNode2 = create_list_node(1);
ListNode* pNode3 = create_list_node(7);
ListNode* pNode4 = create_list_node(2);
ListNode* pNode5 = create_list_node(7);
ListNode* pNode6 = create_list_node(1);
ListNode* pNode7 = create_list_node(1);
//    ListNode* pNode8 = create_list_node(45);
//    ListNode* pNode9 = create_list_node(-7);

//连接结点
connect_list_node(pNode1,pNode2);
connect_list_node(pNode2,pNode3);
connect_list_node(pNode3,pNode4);
connect_list_node(pNode4,pNode5);
connect_list_node(pNode5,pNode6);
connect_list_node(pNode6,pNode7);
//    connect_list_node(pNode7,pNode8);
//    connect_list_node(pNode8,pNode9);

PalindromeList test;

bool flag=test.chkPalindrome(pNode1);
cout<<flag<<endl;

}

int main()
{
test();
return 0;
}```
fcyh | 园豆：568 (小虾三级) | 2017-11-06 09:07

您需要登录以后才能回答，未注册用户请先注册