LEEDCODE 234
来源:互联网 发布:流量监控软件推荐 编辑:程序博客网 时间:2024/05/21 21:40
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
刚开始没住时间复杂度和空间复杂度:
/** * 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) { ListNode* tempHead = head; int count = 0; while(tempHead) { ++count; tempHead = tempHead->next; } stack<ListNode*> tempStack; tempHead = head; for(int i = 1; i <= count/2; ++i) { tempStack.push(tempHead); tempHead = tempHead->next; } if(count % 2 ) tempHead = tempHead->next; while(tempHead) { if(tempStack.top()->val != tempHead->val) return false; else { tempStack.pop(); tempHead = tempHead->next; } } return true; }};如果要求时间和空间复杂度:
将前面一般逆序,再比。空间复杂度为0(1)
/** * 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( NULL == head || NULL == head->next ) return true; ListNode* tempHead = head; int count = 0; while(tempHead) { ++count; tempHead = tempHead->next; } ListNode* pre = NULL; ListNode* nxt = head; for(int i = 1; i <= count/2; ++i) { tempHead = nxt->next; nxt->next = pre; pre = nxt; nxt = tempHead; } if(count % 2 ) nxt = nxt->next; while(nxt) { if(nxt->val != pre->val) return false; else { pre = pre->next; nxt = nxt->next; } } return true; /* stack<ListNode*> tempStack; tempHead = head; for(int i = 1; i <= count/2; ++i) { tempStack.push(tempHead); tempHead = tempHead->next; } if(count % 2 ) tempHead = tempHead->next; while(tempHead) { if(tempStack.top()->val != tempHead->val) return false; else { tempStack.pop(); tempHead = tempHead->next; } } return true;*/ }};
0 0
- LEEDCODE 234
- Leedcode
- leedcode
- [LeedCode OJ]#234 Palindrome Linked List
- Leedcode题解
- LeedCode:Sort List
- Word Break (leedcode)
- LeedCode—MinStack
- LEEDCODE: Clone Graph
- leedcode 3Sum
- LeedCode:Rotate List
- [LeedCode OJ]#120 Triangle
- [LeedCode OJ]#46 Permutations
- leedcode: Course Schedule
- 19.1 leedcode 代码位置
- LeedCode 87. Scramble String
- leedCode 335 Self Crossing
- 【算法题】Leedcode 72
- POJ 1330 Nearest Common Ancestors【LCA】
- 源表含时间戳、做逻辑删除的情况,数据同步ETL方案分享
- (java)判断一个字符串是否是合法的ipv4地址
- vagrant操作详解
- UVALive 7528(2015德黑兰区域赛) Beehive
- LEEDCODE 234
- 递归实现排列组合问题
- IOS学习 collectionView 的创建
- 利用URL实现简单下载网页的功能
- HDU 2034 人见人爱A-B(坑呀...格式)
- 利用Filter 过滤字符编码的格式
- XP下vs2008-qt4.8.6编译Qgis:qwt编译
- 软件工程感想
- Prim算法