LeetCode----Palindrome Linked List
来源:互联网 发布:艾瑞社交数据研究报告 编辑:程序博客网 时间:2024/04/30 23:34
题目描述:
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,*fast;
slow=head;
fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL){
fast=fast->next->next;
slow=slow->next;
}
ListNode *re_head=slow->next;
slow->next=NULL;
ListNode *p1,*p2,*p3;
p1=p2=re_head;
p3=re_head->next;
while(p3!=NULL){
p2=p3;
p3=p3->next;
p2->next=p1;
p1=p2;
}
re_head->next=NULL;
re_head=p2;
while(re_head!=NULL&&head!=NULL){
if(re_head->val!=head->val)
return false;
re_head=re_head->next;
head=head->next;
}
return true;
}
};
- LeetCode Palindrome Linked List
- LeetCode - Palindrome Linked List
- leetcode: Palindrome Linked List
- Leetcode: Palindrome Linked List
- leetcode:Palindrome Linked List
- [LeetCode] Palindrome Linked List
- LeetCode || Palindrome Linked List
- 【leetcode】Palindrome Linked List
- LeetCode-Palindrome Linked List
- Leetcode|Palindrome Linked List
- [leetcode] Palindrome Linked List
- [LeetCode]Palindrome Linked List
- [Leetcode]Palindrome Linked List
- [leetcode] Palindrome Linked List
- [leetCode] Palindrome Linked List
- LeetCode----Palindrome Linked List
- LeetCode:Palindrome Linked List
- LeetCode Palindrome Linked List
- 在服务器 IIS7.0上配置发布网站 遇到404 或401错误
- android byte[] 和short[]的转换
- eclipse-各种设置
- Maven常用的配置
- iOS图片缓存库基准对比
- LeetCode----Palindrome Linked List
- 1分钟搭建教学直播点播平台
- mysql MyISAM表锁
- 华为OJ(字符串合并处理)
- 前台页面传到后台的中文数据出现乱码问题
- OPenGL/3D渲染/shader
- 为什么docker还不能广泛用于生产中
- springMVC(1) 编写springMVC的HelloWorld
- 访问者——对象行为模式