leetcode 234. Palindrome Linked List 回文链表的判断 + 双指针
2017-09-25 14:38
471 查看
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?
建议和leetcode 680. Valid Palindrome II 去除一个字符的回文字符串判断 + 双指针 一起学习
反转链表判断即可。
代码如下:
下面是C++的做法,本题的题意就是使用双指针来分割链表,然后反转链表来判断回文链表
代码如下:
Follow up:
Could you do it in O(n) time and O(1) space?
建议和leetcode 680. Valid Palindrome II 去除一个字符的回文字符串判断 + 双指针 一起学习
反转链表判断即可。
代码如下:
/*class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }*/ /* * 回文链表的判断 * 这个问题的关键是O(1)的内存 * 其实可以使用快慢指针分割链表 * 可以使用栈判断,但是内存使用多了 * 所以反转链表即可 * */ public class Solution { public boolean isPalindrome(ListNode head) { if(head==null || head.next==null) return true; ListNode slow=head,fast=head; while(fast!=null && fast.next!=null) { slow=slow.next; fast=fast.next.next; } //奇数个元素 if(fast!=null) slow=slow.next; slow=reverList(slow); //回文判断 while(slow!=null) { if(head.val!=slow.val) return false; head=head.next; slow=slow.next; } return true; } /* * 反转链表需要好好记一下, * 反思一下 * */ ListNode reverList(ListNode head) { ListNode pre=null; while(head!=null) { ListNode next=head.next; head.next=pre; pre=head; head=next; } return pre; } }
下面是C++的做法,本题的题意就是使用双指针来分割链表,然后反转链表来判断回文链表
代码如下:
#include <iostream> #include <algorithm> #include <vector> #include <set> #include <string> #include <map> using namespace std; /* 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; vector<int> one; ListNode* i = head; while (i != NULL) { one.push_back(i->val); i = i->next; } int j = 0, k = one.size() - 1; whil 4000 e (j < k) { if (one[j] != one[k]) return false; else { j++; k--; } } return true; } };
相关文章推荐
- leetcode - 234. Palindrome Linked List【判断回文链表 + 双指针 + O(1)空间复杂度】
- 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 回文链表 Java
- LeetCode 234. Palindrome Linked List (回文链表)
- [分析总结:leetcode-Palindrome Linked List] 给定单链表,判断链表是否为回文。
- 234. Palindrome Linked List 判断链表是否回文(C++解决)
- LeetCode234_PalindromeLinkedList (判断是否为回文链表) Java题解
- [LeetCode] 234. Palindrome Linked List 回文链表
- Palindrome Linked List - LeetCode 判断一个链表是否是回文结构
- leetcode 328 --Odd Even Linked List 链表 双指针 移动节点
- 234. Palindrome Linked List&回文链表
- (LeetCode)Palindrome Linked List --- 单链表回文
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- 234. Palindrome Linked List 回文链表
- LeetCode OJ:Palindrome Linked List(回文链表判断)
- leetcode--Linked List Cycle--判断链表是否有环