Palindrome Linked List
2015-08-12 21:14
477 查看
Description:
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?
Solution:
class Solution { public: bool isPalindrome(ListNode* head) { if (!head) return true; auto slow = head; auto fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // reverse right half of list ListNode dummy(0); while (slow) { auto next = slow->next; slow->next = dummy.next; dummy.next = slow; slow = next; } auto rev = dummy.next; while (rev) { if (rev->val != head->val) return false; rev = rev->next; head = head->next; } return true; } };
相关文章推荐
- 一个丝滑的全屏滑动返回手势
- dapper-dot-net/Dapper NET40/SqlMapper.cs
- 黑马程序员------OC中类的声明和实现
- 第十八天 doGet和doPost
- 【工业串口和网络软件通讯平台(SuperIO)教程】五.二次开发图形显示界面
- CS/BS模式
- UITabelBar
- 24.Swap Nodes in Pairs (List; Two-Pointers)
- POJ 1903 Jurassic Remains -- 中途相遇法
- UI05 _ 播放MP3格式的歌曲
- Service的使用(二)之与activity的通讯
- IP寻址和子网运算
- 时间复杂度
- jsoup html
- C++里的组合与聚合关系
- 8-12
- jstree动态生成树
- [CareerCup] 5.3 Next Binary Representation 下一个二进制表达
- mongo VUE 操作
- 记一次线上性能优化