LeetCode *** 234. Palindrome Linked List
来源:互联网 发布:java开源门户网站 编辑:程序博客网 时间:2024/05/29 04:26
题目:
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?
分析:
如果要得到一个在中间的值,可以考虑一个走一步,一个走两步。
代码:
O(n)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; vector<int> detail; while(head){ detail.push_back(head->val); head=head->next; } int len=detail.size(); for(int i=0;i<len/2;++i){ if(detail[i]!=detail[len-1-i])return false; } return true; }};
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 *fast=head,*slow=head; while(fast->next!=NULL&&fast->next->next!=NULL){ slow=slow->next; fast=fast->next->next; } slow=reverse(slow->next); while(slow!=NULL){ if(head->val!=slow->val)return false; head=head->next; slow=slow->next; } return true; } ListNode *reverse(ListNode *head){ ListNode *res=NULL; ListNode *tmp=NULL; while(head!=NULL){ tmp=head->next; head->next=res; res=head; head=tmp; } return res; }};
0 0
- [leetcode] 234.Palindrome Linked List
- [LeetCode]234.Palindrome Linked List
- [leetcode] 234.Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [leetcode] 234. Palindrome Linked List
- 234. Palindrome Linked List LeetCode
- LeetCode--234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- leetcode 234. Palindrome Linked List
- LeetCode *** 234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- leetcode-234. Palindrome Linked List
- LeetCode-234.Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [Leetcode]234. Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- 正则表达式
- Echarts扩展之ajax异步加载tooltip数据
- 蛇形矩阵
- 数据存储封装—支持内存和本地缓存
- win7通过samba实现与linux的资源共享
- LeetCode *** 234. Palindrome Linked List
- GDUT 积木积水(栈)
- eclipse注释乱码
- 深度神经网络导论Introduction to Deep Neural Networks
- RoboCup2D team_logo
- python全局变量的使用错误
- 10w分区表,hive能跑,sparksql运行也完全能跑起来
- 注册表操作监控x86
- ndk 开发系列