【leetcode】234. Palindrome Linked List
来源:互联网 发布:尚学堂 js 编辑:程序博客网 时间:2024/05/29 04:39
一、题目描述
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),空间复杂度为o(1)想了很久,确实不太好实现。后来看了讨论区才发现,原来这么巧妙!
通过一个slow和一个fast指针找到链表的中间位置,然后将后半部的链表进行逆置,最后遍历半个链表,看从左半边链表遍历和从右半边链表的逆置链表遍历是否一致。如果所有节点的值都相等,那么就是回文的。
c++代码(28ms,20.05%)
/** * 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=head; ListNode* fast=head; while(fast->next!=NULL && fast->next->next!=NULL){ slow=slow->next; fast=fast->next->next; }//while slow->next=reverseList(slow->next); slow=slow->next; while(slow){ if(head->val != slow->val) return false; head=head->next; slow=slow->next; } return true; } ListNode* reverseList(ListNode* root){ ListNode* pre=NULL; ListNode* next=NULL; while(root){ next=root->next; root->next=pre; pre=root; root=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
- HTML5 语义元素
- mysql之delete删除记录后数据库大小不变
- 【C#】32. 使用EF(EntityFramework)连接Mysql,MVC开发
- 【一天一道LeetCode】#104. Maximum Depth of Binary Tree
- java基础知识之常量与变量
- 【leetcode】234. Palindrome Linked List
- Windows下的SVN安装及使用
- Linux开放端口
- mac中github使用.ppk密钥通过ssh协议clone代码
- Leetcode 116. Populating Next Right Pointers in Each Node
- c++中抽象类与接口的区别
- 数据系统架构——Lambda architecture(Lambda架构)
- javaweb学习总结(六)——Servlet开发(二)
- 九度OJ 1022 游船出租