#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* createList(){ // 建立链表
int val[] = {1,2,3,3,2,1};
int len = sizeof(val)/sizeof(val[0]);
ListNode* tempNode=NULL;
ListNode* firstNode=NULL;
for(int i=0;i<len;++i){
ListNode* node = new ListNode(val[i]);
if(tempNode!=NULL){
tempNode->next = node;
}else{
firstNode=node;
}
tempNode = node;
}
ListNode* pNode=firstNode;
for(int i=0;i<len;++i){
pNode=pNode->next;
}
return firstNode;
}
bool isPalindrome(ListNode* head){ // 判断是否是回文链表
int listLen;
bool isEmpty = false;
bool isPalindrome=true;
ListNode* pNode = head;
if(pNode==NULL){
isEmpty = true;
}
for(listLen=0;pNode->next!=NULL;++listLen){
pNode=pNode->next;
}
if(!isEmpty){
++listLen;
}
int nodeVal[listLen];
pNode=head;
for(int i=0;i<listLen;++i){
nodeVal[i]=pNode->val;
pNode=pNode->next;
}
for(int i=0;i<(listLen/2);++i){
if(nodeVal[i]!=nodeVal[listLen-1-i]){
isPalindrome=false;
}
}
return isPalindrome;
}
ListNode* reverseList(ListNode* head){ // 反转单向链表
int listLen;
bool isEmpty = false;
ListNode* pNode = head;
if(pNode==NULL){
isEmpty = true;
}
for(listLen=0;pNode->next!=NULL;++listLen){
pNode=pNode->next;
}
if(!isEmpty){
++listLen;
}
int nodeVal[listLen];
pNode=head;
for(int i=0;i<listLen;++i){
nodeVal[i]=pNode->val;
pNode=pNode->next;
}
ListNode* tempNode=NULL;
ListNode* firstNode=NULL;
for(int i=listLen-1;i>=0;--i){
ListNode* node = new ListNode(nodeVal[i]);
if(tempNode!=NULL){
tempNode->next = node;
}else{
firstNode=node;
}
tempNode = node;
}
pNode=firstNode;
for(int i=0;i<listLen;++i){
pNode=pNode->next;
}
return firstNode;
}
};
int main(int argc, char const *argv[])
{
Solution obj;
ListNode* head = obj.createList();
if (obj.isPalindrome(head)){
printf("Yes\n");
}else{
printf("No\n");
}
return 0;
}
转载于:https://www.cnblogs.com/locbytes/p/10330152.html