Palindrome Linked List
2015-07-12 15:40
204 查看
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(NULL==head||NULL==head->next) return 1;
int len=0;
stack<ListNode*>s;
ListNode *temp,*p=head;
while(p)
{
p=p->next;
len++;
}
ListNode* head1=head;
int i=1;
s.push(head1);
while(i<len/2)
{
head1=head1->next;
s.push(head1);
i++;
}
if(len%2==0) //必须判断奇偶;
{
head1=head1->next;
}
else{
head1=head1->next->next;
}
while(!s.empty())
{
temp=s.top();
s.pop();
if(temp->val==head1->val)
head1=head1->next;
else return 0;
}
return 1;
}
};
这个找中点有点慢,如果用双指针的话,fast=fast->next->next; slow=slow->next->next; 更快
public:
bool isPalindrome(ListNode* head) {
if(NULL==head||NULL==head->next) return 1;
int len=0;
stack<ListNode*>s;
ListNode *temp,*p=head;
while(p)
{
p=p->next;
len++;
}
ListNode* head1=head;
int i=1;
s.push(head1);
while(i<len/2)
{
head1=head1->next;
s.push(head1);
i++;
}
if(len%2==0) //必须判断奇偶;
{
head1=head1->next;
}
else{
head1=head1->next->next;
}
while(!s.empty())
{
temp=s.top();
s.pop();
if(temp->val==head1->val)
head1=head1->next;
else return 0;
}
return 1;
}
};
这个找中点有点慢,如果用双指针的话,fast=fast->next->next; slow=slow->next->next; 更快
相关文章推荐
- 黑马程序员 集合类
- C语言中函数
- ubuntu将命令写在一个文件里,执行文件,source命令
- HDU 3549 Flow Problem 流问题(最大流,入门)
- Android开发(二十八)——基础功能函数
- 不同品牌无线路由器 无线级联 配置案例
- 1603 - Square Destroyer
- 字符串
- 缘来由天——我在武汉理工大的两年
- 操作数据
- java并发6-小结
- Android开发(二十七)——android:layout_weight的真实含义
- 25匹马,5个赛道,取前3
- 四种方案解决ScrollView嵌套ListView问题
- 实例说明RPC的使用
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- Android Studio 设置编码
- 理解一般指针和指向指针的指针
- hdu 1789 Doing Homework again(贪心)
- 深入浅出Redis04使用Redis数据库(lists类型)