(1) Swap Nodes in Pairs
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode begin(0);
begin.next=head;
ListNode* tmp= new ListNode(0);
tmp->next=new ListNode(0);
ListNode *first,*second,*cur;
cur=&begin;
if(!head || !head->next)
return head;
while(cur->next && cur->next->next)
{
tmp->val=cur->next->next->val;
tmp->next->val=cur->next->val;
first=tmp;
tmp=cur->next;
second=cur->next->next->next;
cur->next=first;
cur->next->next->next=second;
cur=cur->next->next;
}
return begin.next;
}
};
(2) Symmetric Tree
recursively
class Solution {
private:
bool check(TreeNode *a, TreeNode *b){
if(!a && !b) return true;
if(!a && b) return false;
if(a && !b) return false;
return (a->val==b->val) && check(a->left,b->right) && check(a->right,b->left);
}
public:
bool isSymmetric(TreeNode *root) {
if(!root || !root->left && !root->right)
return true;
return check(root->left,root->right);
}
};
iteratively
class Solution {
public:
bool isSymmetric(TreeNode *root) {
if(!root || !root->left && !root->right)
return true;
queue<TreeNode*> left,right;
TreeNode *a,*b;
left.push(root->left);
right.push(root->right);
while(!left.empty() && !right.empty())
{
a=left.front();b=right.front();
left.pop();right.pop();
if(!a && !b) continue;
if(!a || !b) return false;
if(a->val!=b->val) return false;
left.push(a->left);left.push(a->right);
right.push(b->right);right.push(b->left);
}
if(left.empty() && right.empty())
return true;
}
};
(3) Gray Code
规律参考[1]:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> ret;
ret.push_back(0);
for(int i=0; i<n;i++){
int highest = 1<<i;
int len = ret.size();
for(int i=len -1; i>=0; i--){
ret.push_back(highest+ret[i]);
}
}
return ret;
}
};
还有一种最简数学解[2]。
小结:leetcode完成达到了50题,马克一下。
参考:
[1] http://blog.csdn.net/sbitswc/article/details/20110655
[2] http://blog.csdn.net/doc_sgl/article/details/12251523