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

#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[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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值