234. Palindrome Linked List
2016-05-15 13:43
267 查看
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
首先定义快指针和慢指针,找到中间节点。
然后将中间节点和尾节点之间的节点进行翻转。
判断是否为回文节点。
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
首先定义快指针和慢指针,找到中间节点。
然后将中间节点和尾节点之间的节点进行翻转。
判断是否为回文节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { if(head==NULL||head->next==NULL) return true; ListNode* slow=head; ListNode* fast=head; while(fast!=NULL&&fast->next!=NULL)//找到中间节点 { fast=fast->next->next; slow=slow->next; } if(fast==NULL)//说明节点数为偶数 slow=reverseList(slow); else slow=reverseList(slow->next); while(slow!=NULL) { if(slow->val!=head->val) return false; slow=slow->next; head=head->next; } return true; } ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode* node=reverseList(head->next); head->next->next=head; head->next=NULL; return node; } };
相关文章推荐
- linux常用文本编辑器nano/vi/vim
- 学习笔记之Arcgis server开发中identify查询结果显示问题
- Android学习第十一周_gradle、NDK和依赖
- 结构体内存对齐
- XenServer 6.5实战系列:Creating a VM Template from a VM Snapshot
- 1006
- 手机那点事!已有高人把常见的不常见的坑都给找出来了,我就随便转一下了
- 前缀++ 后缀++ 运算符重载
- Freemarker第一次实际项目使用遇到的一些问题
- 如何在自己的CSDN博客中增添【高大上】的博客栏目?
- javascript页面操作
- javascript页面操作
- XenServer 6.5实战系列:Creating a VM Template from an Existing VM
- VS 2015 拖动numericUpDown控件VS无响应(包括VS2013)
- MyBatis学习--高级映射
- coocs2dx 2.0 和3.0版本区别
- Spark Broadcast运行机制解密(42)
- Java:网上超市购物结算功能模拟
- Tensorflow MNIST浅层神经网络的解释和答复
- Tensorflow MNIST浅层神经网络的解释和答复