203. Remove Linked List Elements
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != NULL){
if(cur->next->val == val){
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}else{
cur = cur->next;
}
}
return dummyHead->next;
}
707. Design Linked List
class MyLinkedList {
private:
struct Node{
int val;
Node* next;
Node(int val):val(val), next(NULL){}
};
Node* dummy;
int size;
public:
MyLinkedList() {
dummy = new Node(0);
size = 0;
}
int get(int index) {
if(index >= size || index < 0)
return -1;
Node* cur = dummy->next;
for(int i=0; i<index; i++){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
Node* newNode = new Node(val);
Node* tmp = dummy->next;
dummy->next = newNode;
newNode->next = tmp;
size++;
}
void addAtTail(int val) {
Node* newNode = new Node(val);
Node* cur = dummy;
for(int i=0; i<size; i++){
cur = cur->next;
}
cur->next = newNode;
size++;
}
void addAtIndex(int index, int val) {
Node* newNode = new Node(val);
Node* cur = dummy;
if(index > size) return;
if(index <= size){
for(int i=0; i<index; i++){
cur = cur->next;
}
Node* tmp = cur->next;
cur->next = newNode;
newNode->next = tmp;
}
size++;
}
void deleteAtIndex(int index) {
if(index >= size || index < 0) return;
Node* cur = dummy;
for(int i=0; i<index; i++){
cur = cur->next;
}
Node* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
size--;
}
};
不要忘记增加节点和删除节点的时候size也要变化
206. Reverse Linked List
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tmp;
ListNode* cur = head;
ListNode* pre = NULL;
while(cur != NULL){
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
要稍微注意一下最后返回的是哪个值
509. Fibonacci Number
class Solution {
public:
int fib(int n) {
if(n <= 1) return n;
vector<int> dp(n+1);
dp[0] = 0;
dp[1] = 1;
for(int i=2; i<=n; i++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
70. Climbing Stairs
class Solution {
public:
int climbStairs(int n) {
if(n <= 1) return n;
vector<int> dp(n+1);
dp[1] = 1;
dp[2] = 2;
for(int i=3; i<=n; i++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
为什么要写第一句n<=1?
因为如果不写,当遇到n=1的时候会运行dp[2],但是vector是没有dp[2]的,就会出现错误
746. Min Cost Climbing Stairs
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
vector<int> dp(cost.size()+1);
dp[0]=0;
dp[1] = 0;
for(int i=2; i<=cost.size(); i++){
dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
}
return dp[cost.size()];
}
};