234.回文链表
题目链接
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *h = head;
ListNode *f = new ListNode(0);
ListNode *s = new ListNode(0);
f->next = s->next = h;
while(f && f->next){
s = s->next;
f = f->next->next;
}
ListNode *pre = NULL;
ListNode *nxt;
while(true){
nxt = s->next;
s -> next = pre;
pre = s ;
if(nxt)s = nxt;
else break;
}
while(h!=NULL){
if(s ->val != h ->val)return false;
s = s->next;
h = h->next;
}
return true;
}
};
234.二叉搜索树的最近公共祖先
题目链接
由于这个数据结构建的很挫,所以也用不到什么LCA的技巧
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int l = min(p->val,q->val);
int r = max(p->val,q->val);
while(true){
if(root->val>r)root = root->left;
else if(root->val < l)root = root->right;
else return root;
}
}
};