[Leetcode] #234 Palindrome Linked List
来源:互联网 发布:java面向对象程序设计 编辑:程序博客网 时间:2024/06/07 05:28
Discription:
Given a singly linked list, determine if it is a palindrome.Could you do it in O(n) time and O(1) space?
Solution:
将链表值记录成数组,判断数组是否回文。时间复杂度O(n),空间复杂度O(n)。
class Solution {public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; vector<int> result; ListNode *cur = head; while (cur){ result.push_back(cur->val); cur = cur->next; } int i = 0, j = result.size() - 1; while (i<j){ if (result[i] != result[j]){ return false; } i++; j--; } return true; }};将链表后半段反转与前半段比较,给出两种写法。用双指针找链表中点,注意链表结点是奇数个还是偶数个。时间复杂度O(n),空间复杂度O(1)。
class Solution {public: ListNode *reverseList(ListNode *head){ ListNode *pre = NULL, *temp; while(head){ temp = head->next; head->next = pre; pre = head; head = temp; } return pre; } bool isPalindrome(ListNode* head) { if(!head || !head->next) return true; ListNode *slow = head,*fast = head,*pre = NULL; while(fast && fast->next){ fast = fast->next->next; pre = slow; slow = slow->next; } pre->next = NULL; slow = reverseList(slow); while(head && slow){ if(head->val != slow->val) return false; head = head->next; slow = slow->next; } return true; }};
class Solution {public: ListNode *reverseList(ListNode *head){ ListNode *pre = NULL, *temp; while(head){ temp = head->next; head->next = pre; pre = head; head = temp; } return pre; } bool isPalindrome(ListNode* head) { if(!head || !head->next) return true; ListNode *slow = head,*fast = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; } if(fast){//链表个数为奇数个 slow = reverseList(slow->next); } else{//链表个数为偶数个 slow = reverseList(slow); } while(slow){ if(head->val != slow->val) return false; head = head->next; slow = slow->next; } return true; }};
0 0
- Palindrome Linked List leetcode 234
- 【LeetCode】234 Palindrome Linked List
- Palindrome Linked List (leetcode 234)
- leetcode 234: Palindrome Linked List
- leetcode[234]:Palindrome Linked List
- LeetCode 234Palindrome 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
- [leetcode 234] Palindrome Linked List
- LeetCode 234 Palindrome Linked List
- 2014年10大Web设计趋势
- 关于用for()循环打印一个三角形(菱形)
- openwrt远程登录总结
- 分析AJAX抓取今日头条街拍美图(上)
- 【C#】sqlitehelper类
- [Leetcode] #234 Palindrome Linked List
- 进程和线程的区别和linux运行状态查看简单介绍
- C++的STL之find_first_of
- 内存对齐———结构体
- 欢迎使用CSDN-markdown编辑器
- servlet request getHeader("x-forwarded-for") 获取真实IP
- C#网络电视精灵系统
- [IOS APP]窥破金瓶梅-西门庆真的很好色吗
- Windows下ActiveMQ下载、安装部署