您的位置:首页 > 职场人生

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

2016-12-21 17:24 295 查看
#include <iostream>
#include <stdio.h>
#include <stack>

using namespace std;

/*
问题:编写一个函数,检查链表是否为回文
分析:所谓回文,也就是对称。先找到中间位置处,然后将链表中元素放入栈中
然后从头结点往后,依次取出栈中元素进行比较

输入:
5(链表长度)
1 2 3 2 1
5
1 2 3 2 3
4
1 2 2 1
4
1 2 2 3
输出:
yes
no
yes
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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: