###
首先是定义链表
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) {}
};
203.移除链表
链表的判断主要需要首先考虑head的情况,单独拎出来判断。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while (head != NULL && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* cur = head;
while (cur != NULL && cur->next != NULL) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
else cur = cur->next;
}
return head;
}
};
707.设计链表
二刷依旧感觉很痛苦
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) {}
};
ListNode* _dummyhead;
int size;
MyLinkedList() {
_dummyhead = new ListNode(0);
size = 0;
}
int get(int index) {
if (index >= size || index < 0) {
return -1;
}
ListNode* cur = _dummyhead->next;
while (index--) {
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* newHead = new ListNode(val);
newHead->next = _dummyhead->next;
_dummyhead->next = newHead;
size++;
}
void addAtTail(int val) {
ListNode* newTail = new ListNode(val);
ListNode* cur = _dummyhead;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newTail;
size++;
}
void addAtIndex(int index, int val) {
if (index > size) return;
if (index < 0) index = 0;
ListNode* newNode = new ListNode(val);
ListNode* cur = _dummyhead;
while (index--) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
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;
delete tmp;
size--;
}
};
206.反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tmp;
ListNode* cur = head;
ListNode* pre = NULL;
while (cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};