203.移除链表元素
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8eb68b8ae0c97edb6d65588979a75b71.png)
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* cur = dummy;
while (cur->next != nullptr)
{
if (cur->next->val == val)
{
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else
{
cur = cur->next;
}
}
head = dummy->next;
delete dummy;
return head;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a163e751a9692add7b744115bd518c44.png)
707. 设计链表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4d7dd4be12aec6e9b85f3b9d2b5423a2.png)
class MyLinkedList {
public:
struct ListNode
{
int val;
ListNode* next;
ListNode(int num) : val(num), next(nullptr){}
};
public:
MyLinkedList() {
dummynode_ = new ListNode(0);
size_ = 0;
}
int get(int index) {
if (index < 0 || index >= size_) return -1;
ListNode* cur = dummynode_->next;
for (int i = 0; i < index; i++)
{
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* temp = new ListNode(val);
temp->next = dummynode_->next;
dummynode_->next = temp;
size_++;
}
void addAtTail(int val) {
ListNode* temp = new ListNode(val);
ListNode* cur = dummynode_;
while (cur->next != nullptr)
{
cur = cur->next;
}
cur->next = temp;
size_++;
}
void addAtIndex(int index, int val) {
if (index > size_) return;
ListNode* temp = new ListNode(val);
ListNode* cur = dummynode_;
for (int i = 0; i < index; i++)
{
cur = cur->next;
}
temp->next = cur->next;
cur->next = temp;
size_++;
}
void deleteAtIndex(int index) {
if (index >= size_ || index < 0) return;
ListNode* cur = dummynode_->next;
ListNode* pre = dummynode_;
for (int i = 0; i < index; i++)
{
pre = cur;
cur = cur->next;
}
pre->next = cur->next;
delete cur;
size_--;
}
void print()
{
ListNode* cur = dummynode_;
while (cur->next != nullptr)
{
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
ListNode* dummynode_;
int size_;
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a0d23d1b38af463cd6f81417a5b34a79.png)