Leetcode Palindrome Linked List 234
2016-12-20 18:25
459 查看
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?
Subscribe to see which companies asked this question
题目链接
最开始考虑的是用栈来保存,时间和空间复杂度达到o(n)
继续优化空间,达到常数空间
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question
题目链接
最开始考虑的是用栈来保存,时间和空间复杂度达到o(n)
/** * 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) return true; int cnt=0; ListNode* p = head; while(p){ cnt++; p=p->next; } if(cnt==1) return true; stack<int> s; p = head; int tmpcnt=0; while(p){ tmpcnt++; if(tmpcnt==cnt/2) { s.push(p->val); break; } else{ s.push(p->val); } p=p->next; } if(cnt%2) { p=p->next->next; } else p=p->next; while(p){ if(p->val==s.top()){ p=p->next; s.pop(); } else{ return false; } } return true; } };
继续优化空间,达到常数空间
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { private: ListNode* he; public: bool isPalindrome(ListNode* head) { if(head==NULL || head->next==NULL) return true; else{ he=head; return judge(he); } } bool judge(ListNode* h){ if(h==NULL) return true; if(!judge(h->next)) return false; if(he->val!=h->val) return false; else{ he=he->next; return true; } } };
相关文章推荐
- leetcode234~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 复杂度为时间O(n) 和空间(1)解法
- LeetCode234_PalindromeLinkedList (判断是否为回文链表) Java题解
- 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
- LeetCode234: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 复杂度为时间O(n) 和空间(1)解法