203. 移除链表元素
707. 设计链表
206. 反转链表
203. 移除链表元素
因为在原来的链表上操作要考虑头结点感觉有点麻烦,
于是学习了一下“虚拟头结点”
总而言之就是,先创建个虚拟头结点,让其 next 指向head,
于是就可以批量操作了,一个循环直接解决
至于 delete 的问题,leetcode 不 delete 也是能过的,但是都写 cpp 了那 delete 肯定要养成好习惯
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyhead = new ListNode();
dummyhead->next = head;
ListNode* cur = dummyhead;
while(head != nullptr)
{
if(head->val == val)
{
cur->next = head->next;
delete head;
head = cur->next;
}
else
{
cur = cur->next;
head = head->next;
}
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};
707. 设计链表
这个题还是挺综合的……
写时候有点困,导致犯了个低级错误找了十年……
注意 addAtIndex 函数,index > size 时直接返回......
class MyLinkedList {
private:
struct Node {
int val;
Node* next;
Node() : val(0), next(nullptr) {}
Node(int _val) : val(_val), next(nullptr) {}
};
Node* dummyhead;
int _size = 0;
public:
MyLinkedList() {
dummyhead = new Node(-1);
}
int get(int index) {
Node* cur = dummyhead->next;
for(int i = 0; i < _size; ++i) {
if(i == index) {
break;
}
cur = cur->next;
}
return (index < 0 || index >= _size) ? -1 : cur->val;
}
void addAtHead(int val) {
Node* head = new Node(val);
head->next = dummyhead->next;
dummyhead->next = head;
_size++;
}
void addAtTail(int val) {
Node* cur = dummyhead;
while(cur->next != nullptr) {
cur = cur->next;
}
Node* tail = new Node(val);
cur->next = tail;
_size++;
}
void addAtIndex(int index, int val) {
if(index > 0 && index < _size) {
Node* node = new Node(val);
Node* cur = dummyhead->next;
for(int i = 0; i < _size - 1; ++i) {
if(i + 1 == index) {
node->next = cur->next;
cur->next = node;
}
cur = cur->next;
}
_size++;
}
if(index <= 0) {
addAtHead(val);
}
if(index == _size) {
addAtTail(val);
}
}
void deleteAtIndex(int index) {
if(index < 0 || index >= _size) {
return;
}
Node* cur = dummyhead;
for(int i = 0; i < _size; ++i) {
if(i == index) {
Node* tmp = cur->next;
cur->next = tmp->next;
delete tmp;
}
cur = cur->next;
}
_size--;
}
};
206. 反转链表
这个水,但凡上过数据结构应该都会吧。
明天补一下递归吧……
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while(cur != nullptr)
{
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev == nullptr ? head : prev;
}
};