Leetcode 234. Palindrome Linked List
来源:互联网 发布:php.ini设置文件大小 编辑:程序博客网 时间:2024/06/06 07:08
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?
题目是求单链表是否是回文。根据在平台上测试结果知:12->34->12是回文,而不是说 12->343 ->21是回文,这个概念要搞清楚。解题思路很简单,用两个节点,一个一次遍历一个结点,一个一次两个,找到中点结点,把中点之后的单链表反转然后和前面结点一 一比对。
class Solution {public: bool isPalindrome(ListNode* head) { if(head==NULL||head->next==NULL) return true; ListNode* slow=head; ListNode* fast=head; while(fast->next!=NULL&&fast->next->next!=NULL){ slow=slow->next; fast=fast->next->next; } slow->next=reverseList(slow->next); slow=slow->next; while(slow!=NULL){ if(head->val!=slow->val) return false; head=head->next; slow=slow->next; } return true; } ListNode* reverseList(ListNode* head) { ListNode* pre=NULL; ListNode* next=NULL; while(head!=NULL){ next=head->next; head->next=pre; pre=head; head=next; } return pre; }};
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
- 【spring】AOP注解实现
- Hadoop集群部署介绍
- rw_《计算机是怎样跑起来的》12 章 & 总结
- Android Studio运行程序出现Session ‘app’: Error Launching activity 解决办法
- 【[NOIP2009】靶形数独 题解
- Leetcode 234. Palindrome Linked List
- LintCode:最近公共祖先
- 学习js
- Java垃圾回收机制
- 基础系列(一):命令
- sublime text3环境下的python即时编译插件
- linux实施流量监测工具 mark
- Gym 100960G Youngling Tournament(splay)
- 图论练习册