[LeetCode] Palindrome Linked List
2015-07-26 10:31
344 查看
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) {
ListNode* myHead1 = new ListNode(0);
myHead1->next = head;
int len = getLength(myHead1);
if(len<2){
return true;
}
bool flag = true;
ListNode* myHead2 = new ListNode(0);
ListNode* p = myHead1->next, *q;
for(int i=len/2; i>0; i--){
myHead1->next = p->next;
p->next=myHead2->next;
myHead2->next = p;
p=myHead1->next;
}
p=myHead1->next;
q=myHead2->next;
if(len%2!=0){
p=p->next;
}
while(p!=NULL){
if(p->val!=q->val){
flag = false;
break;
}
p=p->next;
q=q->next;
}
return flag;
}
//注意这里有个表头了
int getLength(ListNode* head){
int count = 0;
while(head->next!=NULL){
head=head->next;
count++;
}
return count;
}
};
方法二的代码如下:
/**
* 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;
ListNode* slow = head;
while(fast!=NULL&&fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
}
//将前半部分
ListNode* myHead = new ListNode(0);
ListNode* p = head, *q;
while(p!=slow){
q = p->next;
p->next = myHead->next;
myHead->next = p;
p = q;
}
p = myHead->next;
q = slow;
if(fast!=NULL){ //表示是奇数个
q= q->next;
}
while(p!=NULL){
if(p->val!=q->val){
return false;
}
p=p->next;
q=q->next;
}
return true;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解