一、Leetcode 203 移除链表元素
题目链接:Leetcode 203
这道题应该就是链表专题里的入门题,为什么这样说,因为他用到了链表操作里经常用到的dummyhead。我在刚开始做的时候忘了dummyhead这个方法,也忘了头节点的定义,误以为头节点就是dummyhead。一开始想的是用一个指针node遍历整个链表就可以,如果node->next->val是target val就删除,但是这个忽略了当前node->val,于是我就在想是不是得用slow和fast一起遍历,再加上dummyhead的方法,这道题就做出来了
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
int i=0;
if(head==nullptr) return nullptr;
ListNode* dummy = new ListNode(0);
dummy->next=head;
ListNode* slow=dummy;
ListNode* fast = head;
while(1){
if(fast->val==val){
slow->next=fast->next;
fast=fast->next;
}else{
slow=slow->next;
fast=fast->next;
}
if(fast==nullptr) return dummy->next;
i++;
}
return dummy;
}
};
二、Leetcode 707 设计链表
题目链接:Leetcode 707
这道题虽然官方给的是medium难度,但是感觉稍微理解该咋做以后完全没有medium的难度,难的在于刚开始的时候是懵的,这是我做第二遍了,刚开始还是有点懵,至于里面具体的函数实现,很简单
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
MyLinkedList() {
dummyhead = new ListNode(0);
size=0;
}
int get(int index) {
if(index>(size-1) || index<0) return -1;
ListNode* node = dummyhead->next;
while(index--){
node=node->next;
}
return node->val;
}
void addAtHead(int val) {
ListNode* add = new ListNode(val);
add->next = dummyhead->next;
dummyhead->next=add;
size++;
}
void addAtTail(int val) {
ListNode* node = dummyhead;
while(node->next!=nullptr){
node=node->next;
}
ListNode* add = new ListNode(val);
add->next=nullptr;
node->next=add;
size++;
}
void addAtIndex(int index, int val) {
if(index>size) return;
if(index<0) index=0;
ListNode* add = new ListNode(val);
ListNode* curr = dummyhead;
while(index--){
curr=curr->next;
}
add->next = curr->next;
curr->next = add;
size++;
}
void deleteAtIndex(int index) {
if (index >= size || index < 0) {
return;
}
ListNode* cur = dummyhead;
while(index--) {
cur = cur ->next;
}
ListNode* tmp = cur->next;
cur->next = cur->next->next;
size--;
}
private:
int size;
ListNode* dummyhead;
};
三、Leetcode 206 反转链表
题目链接:Leetcode 206
206这道题也是跟之前有相似的毛病,知道咋做,能懂百分之八九十,就卡在最后那一点点,刚开始我是定义一个dummyhead指向第一个节点,等到反转的时候错以为把dummyhead变为null就可以让第一个节点node->next置为nullptr,这里犯得就是基础性的问题,特此记录,引以为戒
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* curr1 = dummyhead;
ListNode* curr2 = head;
ListNode* temp;
int i=0;
while (curr2 != nullptr) {
i++;
temp = curr2->next;
curr2->next = curr1;
curr1 = curr2;
curr2 = temp;
}
delete dummyhead;
dummyhead = nullptr;
return curr1;
}
};
总结
今天是打卡的第三天,明显感觉到没有前两天热情高涨了哈哈哈,主要是今天第二个那个707卡的人太久了,有点繁琐这道题,希望后面能尽量坚持下去。

1405

被折叠的 条评论
为什么被折叠?



