Day03——链表
- 掌握链表理论基础
- 203.移除链表元素
- 707.设计链表
- 206.反转链表
链表理论基础:
链表结构体定义:
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}; // 默认构造函数不会初始化成员变量
ListNode(int x) : val(x), next(nullptr) {}
}
链表在内存中是不连续分布的,指针域的指针链接在内存中各个节点。
203.移除链表元素
思路:链表元素删除需要先找到该节点的前一个节点
1.由于删除元素需要先找到前一节点,所以分两种情况(删除头节点和删除子节点)
while(head != nullptr && head->val == val) {
ListNode *tmp = head;
head = head->next;
delete tmp;
tmp = nullptr;
}
ListNode *cur = head;
while(cur->next != nullptr) {
if(cur->next->val == val) {
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
} else
cur = cur->next;
}
- 将头节点转变为子节点保存
ListNode *node= new ListNode();
node->next = head;
ListNode *cur = node;
while(cur->next != nullptr) {
if(cur->next == val) {
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
} else
cur = cur->next;
}
return node;
707. 设计链表
这个好像没啥说的,模拟就完了
class MyLinkedList {
// 定义链表节点结构体
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {};
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* head;
int _size;
public:
MyLinkedList() {
head = new ListNode();
_size = 0;
}
int get(int index) {
if (index > _size) return -1;
ListNode *cur = head;
int a = 0;
// while (cur != nullptr) {
// cout << " " << a++ << " " << cur->val << " ";
// cur = cur->next;
// }
// cout << endl;
cur = head;
while(cur->next != nullptr) {
if (index-- == 0) return cur->next->val;
cur = cur->next;
}
return -1;
}
void addAtHead(int val) {
ListNode *cur = new ListNode(val);
cur->next = head->next;
head->next = cur;
++_size;
}
void addAtTail(int val) {
ListNode *cur = new ListNode(val);
ListNode *tmp = head;
while(tmp->next != nullptr) {
tmp = tmp->next;
}
tmp->next = cur;
++_size;
}
void addAtIndex(int index, int val) {
if (index > _size || index < 0) return;
ListNode *tmp = new ListNode(val);
ListNode *cur = head;
while(index--) {
cur = cur->next;
}
tmp->next = cur->next;
cur->next = tmp;
++_size;
}
void deleteAtIndex(int index) {
if (index >= _size || index < 0) return; // 没搞清楚为什么是 >= size,=size应该也可以删除呀
ListNode *cur = head;
while(index--) {
cur = cur->next;
}
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp = nullptr;
--_size;
}
};
206. 反转链表
思路:链表反转只需要改变链表连接顺序,
1.即使用临时节点保存net节点,——net = cur->next;
2.断开cur 和 net之间的连接,将cur指向新的链表pre——cur->net = pre;
3.更新节点,使用pre替换cur,将cur指向旧链表地址
ListNode *pre = nullptr;
ListNode *cur = head;
ListNode *net = nullptr;
while(cur != nullptr){
net = cur->next;
cur->next = pre;
pre = cur;
cur = net;
}
return pre;