class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newHead = NULL;
ListNode* p = head;
while (p) {
ListNode* temp = p->next;
p->next = newHead;
newHead = p;
p = temp;
}
return newHead;
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* p = l1;
ListNode* q = l2;
ListNode* ansHead = new ListNode(0);
ListNode* ansTail = ansHead;
while (p || q) {
moveToAns(ansTail, getSmallerOne(p, q));
}
return ansHead->next;
}
ListNode*& getSmallerOne(ListNode*& a, ListNode*& b) {
if (!a)
return b;
else if (!b)
return a;
else
return a->val < b->val ? a : b;
}
void moveToAns(ListNode*& ansTail, ListNode*& head) {
ListNode* newHead = head->next;
ansTail->next = head;
ansTail = head;
ansTail->next = NULL;
head = newHead;
}
};
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
if (!B)
return false;
return traverseTree(A, B);
}
bool traverseTree(TreeNode* A, TreeNode* B) {
if (isSubStructureCore(A, B))
return true;
if (A->left != NULL && traverseTree(A->left, B))
return true;
if (A->right != NULL && traverseTree(A->right, B))
return true;
return false;
}
bool isSubStructureCore(TreeNode* A, TreeNode* B) {
if (!A && !B)
return true;
if (A && B) {
if (A->val != B->val)
return false;
else
return isSubStructureCore(A->left, B->left)
&& isSubStructureCore(A->right, B->right);
} else if (!B) {
return true;
} else {
return false;
}
}
};