203. 移除链表元素
文章:代码随想录 (programmercarl.com)
视频:https://www.bilibili.com/video/BV18B4y1s7R9
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//删除头结点
while (head != NULL && head->val == val)
{
ListNode* temp = head;
head = head->next;
delete temp;
}
//删除非头结点
ListNode* cur = head;
while (cur != NULL && cur->next != NULL)
{
if (cur->next->val == val)
{
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else {
cur = cur->next;
}
}
return head;
}
};
707. 设计链表
文章:代码随想录 (programmercarl.com)
视频:https://www.bilibili.com/video/BV1FU4y1X7WD
class MyLinkedList {
public:
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* _dummyHead;
int _size;
MyLinkedList() {
_dummyHead = new ListNode(0);
_size = 0;
}
int get(int index) {
if (index > (_size - 1) || index < 0) {
return -1;
}
ListNode* cur = _dummyHead->next;
while (index-- != 0)
{
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* newNode = new ListNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
_size++;
}
void addAtTail(int val) {
ListNode* cur = _dummyHead;
ListNode* newNode = new ListNode(val);
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if (index > _size)
{
return;
}
if (index < 0)
{
index = 0;
}
ListNode* cur = _dummyHead;
while (index-- != 0)
{
cur = cur->next;
}
ListNode* newNode = new ListNode(val);
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* temp = cur->next;
cur->next = cur->next->next;
delete temp;
_size--;
}
};
206. 反转链表
文章:代码随想录 (programmercarl.com)
视频:https://www.bilibili.com/video/BV1nB4y1i7eL
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* temp;
while (cur != NULL)
{
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
//对每一步的分析:
pre = null; cur = 1; temp = cur->next = 2; cur->next = pre = null; 1->null; pre = cur = 1; cur = temp = 2;
pre = 1; cur = 2; temp = cur->next = 3; cur->next = pre = 1; 2->1;pre = cur = 2; cur = temp = 3;
pre = 2; cur = 3; temp = cur->next = 4; cur->next = pre = 2;3->2;pre = cur = 3; cur = temp = 4;
pre = 3; cur = 4; temp = cur->next = 5; cur->next = pre = 3;4->3;pre = cur = 4; cur = temp = 5;
pre = 4; cur = 5; temp = cur->next = null; cur->next = pre = 4; 5->4; pre = cur = 5; cur = temp = null;
return pre;