程序员面试金典: 9.2链表 2.7检查链表是否为回文

来源:互联网 发布:vps绑定域名 编辑:程序博客网 时间:2024/06/05 16:30
#include <iostream>#include <stdio.h>#include <stack>using namespace std;/*问题:编写一个函数,检查链表是否为回文分析:所谓回文,也就是对称。先找到中间位置处,然后将链表中元素放入栈中      然后从头结点往后,依次取出栈中元素进行比较输入:5(链表长度)1 2 3 2 151 2 3 2 341 2 2 141 2 2 3输出:yesnoyes no关键:1 可以采用翻转整个链表并比较,如果两个链表相同2 可以采用快慢指针,将慢指针的节点存入栈中,当快指针走到链表末尾时,慢  指针走到链表中间,此时比较慢指针对应元素和栈顶元素是否相等即可,这个只需要遍历一遍*/typedef struct Node{int value;Node* pNext;}Node;//构建连边,按照尾插法来做,返回节点值到出现次数的映射void buildList(int* pArray , Node* head , int num){if(pArray == NULL){return;}if(head == NULL){return;}//尾插法: 保留最后一个结尾节点,将新生成的节点插入在结尾节点,并令结尾节点为当前节点Node* pLast = head;//int num = sizeof(pArray) / sizeof(int);for(int i = 0 ; i < num ; i++){int value = *(pArray + i);Node* pNode = new Node();pNode->value = value;pLast->pNext = pNode;pLast = pNode;}}void printList(Node* pHead){if(NULL == pHead){return;}Node* pNode = pHead->pNext;while(pNode){cout << pNode->value << " ";pNode = pNode->pNext;}cout << endl;}void releaseList(Node* pHead){if(NULL == pHead){return;}Node* pNode = pHead->pNext;Node* pPrevious = pHead;while(pNode){Node* pDeleteNode = pNode;pPrevious->pNext = pNode->pNext;pNode = pNode->pNext;pPrevious = pPrevious->pNext;delete pDeleteNode;}//删除头结点delete pHead;}//是否是环形链表bool isPalindromeList(Node* pHead){stack<int> stackData;if(pHead == NULL){return false;}int length = 0;Node* pNode = pHead->pNext;while(pNode){stackData.push(pNode->value);length++;pNode = pNode->pNext;}//下面比较pNode = pHead->pNext;int count = 0;while(pNode){if(count >= length/2){break;}int value = stackData.top();stackData.pop();if(pNode->value != value){return false;}pNode = pNode->pNext;count++;}return true;}int main(int argc, char* argv[]){int n ;while(cin >> n ){int* pArr = new int[n];for(int i = 0 ; i < n ; i++){cin >> pArr[i];}Node* pHead = new Node();buildList(pArr , pHead , n);bool isPlaindrome = isPalindromeList(pHead);if(isPlaindrome){cout << "yes" << endl;}else{cout << "no" << endl;}//printList(pHead);releaseList(pHead);delete[] pArr;}system("pause");return 0;}

0 0
原创粉丝点击