代码随想录打卡第三天, 新手自我记录一下刷题历程, 仅为自我打卡使用.
今天比较晚才完成任务.
链表刚上手还是不太熟, 前两题都做出来了, 第三题翻转链表翻车了, 掉进怪圈憋了好久最后看了答案发现竟如此简单, 递归法很精妙, 我完全没想到.
虚拟头节点很巧妙, 刚上手我没想到, 自己写的时候就是分情况是还是不是头节点讨论的.
删除的时候释放内存咋写我也没想出, 这里是看了carl哥答案之后补上的, 看来还是不能活学活用啊!
另外测试时候在main主函数里写测试用例写了半天hhhh.
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head != nullptr && head->val == val){
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* currentNode = head;
while(currentNode != nullptr && currentNode->next != nullptr){
if (currentNode->next->val == val){
ListNode* tmp = currentNode->next;
currentNode->next = currentNode->next->next;
delete tmp;
}
else{
currentNode = currentNode->next;
}
}
return head;
}
};
刚看题时候一阵头大, 仔细看还是不难, 把链表常用的几个操作基本上都覆盖到了.
class MyLinkedList {
public:
MyLinkedList() {
dummyHead = new ListNode(0);
size = 0;
}
~MyLinkedList() {
ListNode* cur = dummyHead;
while (cur) {
ListNode* temp = cur;
cur = cur->next;
delete temp;
}
}
int get(int index) {
if (index > size - 1 || index < 0){
return -1;
}
ListNode* cur = dummyHead->next;
for (int i = 0; i < index; ++i){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* cur = dummyHead->next;
dummyHead->next = new ListNode(val);
dummyHead->next->next = cur;
size++;
}
void addAtTail(int val) {
ListNode* cur = dummyHead;
for (int i = 0; i < size; ++i){
cur = cur->next;
}
cur->next = new ListNode(val);
size++;
}
void addAtIndex(int index, int val) {
if (index > size){
return;
}
if(index < 0) {
index = 0;
}
ListNode* cur = dummyHead;
for (int i = 0; i < index; ++i){
cur = cur->next;
}
ListNode* tmp = cur->next;
cur->next = new ListNode(val);
cur->next->next = tmp;
size++;
}
void deleteAtIndex(int index) {
if (index > size - 1 || index < 0){
return;
}
ListNode* cur = dummyHead;
for (int i = 0; i < index; ++i){
cur = cur->next;
}
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
size--;
}
private:
ListNode* dummyHead;
int size;
};
卡了很久, 中间变量该指cur自己还是cur->next卡了半天, 把自己绕晕了, 听carl哥视频反而很好懂.
递归的方法留着二刷时候自己再写一遍.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* last = nullptr;
ListNode* tmp;
while (cur != nullptr){
tmp = cur->next;
cur->next = last;
last = cur;
cur = tmp;
}
return last;
}
};
今天拖的比较久, 第三题出了个门以后回来完成的, 下回要提高效率!