21. 斐波那契数列
https://www.acwing.com/problem/content/19/
class Solution {
public:
int Fibonacci(int n) {
if(n <= 1) return n;
else return Fibonacci(n - 1) + Fibonacci(n - 2);
}
};
16. 替换空格
https://www.acwing.com/problem/content/17/
class Solution {
public:
string replaceSpaces(string &str) {
string res;
for (auto x : str)
if (x == ' ')
res += "%20";
else
res += x;
return res;
}
};
84. 求1+2+…+n
https://www.acwing.com/problem/content/80/
class Solution {
public:
int getSum(int n) {
int num = n;
(n > 0) && (num += getSum(n - 1));
return num;
}
};
28. 在O(1)时间删除链表结点
https://www.acwing.com/problem/content/85/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* next = node->next;
node->val = next->val;
node->next = next->next;
}
};
36. 合并两个排序的链表
https://www.acwing.com/problem/content/34/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(0);
ListNode *cur = dummy;
while (l1 != NULL && l2 != NULL) {
if (l1 -> val < l2 -> val) {
cur -> next = l1;
l1 = l1 -> next;
}
else {
cur -> next = l2;
l2 = l2 -> next;
}
cur = cur -> next;
}
cur -> next = (l1 != NULL ? l1 : l2);
return dummy -> next;
}
};