移除链表就两种方法,用不用虚拟头结点,相对而言,用虚拟头结点是更好理解的,一气呵成,问题不大
带头结点的:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur && cur->next) {
if (cur->next->val == val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return dummyHead->next;
}
};
不带头结点的:
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == nullptr)
return head;
while (head != nullptr && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* cur = head;
while (cur && cur->next) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};
第二题主要是注意i判断index条件和while(index--)在哪里停了,使用虚拟头结点就比较好过了,也是一气呵成
// class ListNode
// {
// public:
// ListNode(int val):val(val), next(nullptr) {}
// private:
// int val;
// ListNode* next;
// }
class MyLinkedList {
public:
MyLinkedList() {
dummyHead = new ListNode(0);
size = 0;
}
int get(int index) {
if (index < 0 || index >= size)
return -1;
ListNode* cur = dummyHead;
while (index--) {
cur = cur->next;
}
return cur->next->val;
}
void addAtHead(int val) {
ListNode* insertNode = new ListNode(val);
ListNode* tmp = dummyHead->next;
dummyHead->next = insertNode;
insertNode->next = tmp;
size++;
}
void addAtTail(int val) {
ListNode* insertNode = new ListNode(val);
ListNode* cur = dummyHead;
while (cur && cur->next) {
cur = cur->next;
}
cur->next = insertNode;
size++;
}
void addAtIndex(int index, int val) {
if (index > size || index < 0)
return;
ListNode* cur = dummyHead;
while (index--) {
cur = cur->next;
}
ListNode* insertNode = new ListNode(val);
ListNode* tmp = cur->next;
cur->next = insertNode;
insertNode->next = tmp;
size++;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
ListNode* cur = dummyHead;
while (index--) {
cur = cur->next;
}
cur->next = cur->next->next;
size--;
}
private:
ListNode* dummyHead;
int size;
};
主要是第三题有点卡主了,一时间想不起来head应该指向哪里,要明确的是链表的最后一个node的指向为空指针,因为在设计node结构体/类时的next的默认构造为nullptr,所以最后一个指向的是空指针,那好,反转之后原来的head应该指向空,利用一个空指针节点,逐渐往下遍历
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* dummyHead = nullptr;
while (cur) {
ListNode* tmp = cur->next;
cur->next = dummyHead;
dummyHead = cur;
cur = tmp;
}
return dummyHead;
}
};