回文链表
来源:互联网 发布:什么是淘宝旺旺号啊 编辑:程序博客网 时间:2024/05/22 04:52
题目描述:
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
思路:将链表前半部分存入vector容器,和后半部分比较,由于不知道链表长度,使用快慢指针来取链表前半部分,注意链表长度为奇数时,跳过中间的元素
/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*/class Palindrome {public: bool isPalindrome(ListNode* pHead) { // write code here ListNode *pFast = pHead; ListNode *pSlow = pHead; vector<int> tmp; //链表长度为偶数 while (pFast != nullptr && pFast->next != nullptr) { tmp.push_back(pSlow->val); pSlow = pSlow->next; pFast = pFast->next->next; } //链表长度为奇数 if (pFast != nullptr) { pSlow = pSlow->next; } //比较前半部分和后半部分 int len = tmp.size(); while (pSlow != nullptr) { if (tmp[--len] != pSlow->val) return false; pSlow = pSlow->next; } return true; }};
阅读全文
0 0
- 字符串回文判断, 链表回文判断
- 链表回文判断
- 回文链表
- 回文链表(Java)
- 回文链表
- 回文链表
- 回文链表
- 判断回文链表
- 回文链表
- LintCode:回文链表
- 回文链表
- 回文链表
- 回文链表
- 回文链表
- 回文链表
- 链表回文
- LintCode:回文链表
- lintcode,回文链表
- mac下 adb :command not found问题解决
- 8皇后问题
- thinkphp5.0学习(七):数据库操作
- Vue 自定义指令
- python 空格替换
- 回文链表
- hadoop 8088端口网页无法打开的原因分析
- Java后端程序员1年工作经验总结
- windows7环境下Eclipse集成Python开发环境+安装TensorFlow
- dexcachelist导致anr
- 八皇后
- 排序算法之快速排序
- Android开发---手机号码输入框(满11位自动跳到下个输入框)
- 深度【文本分类】【关系抽取】模型中,如何读取并处理输出的训练文件(TXT格式)