一、链表理论基础
二、203.移除链表元素
1.题目
2.解决思路
利用while循环和if条件结构,注意:判断时是利用currentNode->next->val做判断
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0);
dummyHead -> next = head;
ListNode* cur = dummyHead;
while(cur->next != NULL){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}
else{
cur = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
三、707.设计链表
1.题目
2.解决思路
图形结合+特例法确定边界
class MyLinkedList {
public:
//定义节点结构体
struct linkNode{
linkNode* next;
int val;
linkNode(int val):val(val),next(nullptr){}
};
MyLinkedList() {
//建立虚节点
dummyNode = new linkNode(0);
size = 0;
}
int get(int index) {
if(index < 0 || index > (size - 1)){
return -1;
}
//建立头节点
linkNode* cur = dummyNode->next;
while(index--){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
linkNode* temp = new linkNode(val);
temp->next = dummyNode->next;
dummyNode->next = temp;
size++;
}
void addAtTail(int val) {
linkNode* temp = new linkNode(val);
linkNode* cur = dummyNode;
while(cur->next){
cur = cur->next;
}
cur->next = temp;
size++;
}
void addAtIndex(int index, int val) {
if (index > size || index < 0) {
return;
}
linkNode* temp = new linkNode(val);
linkNode* cur = dummyNode;
while(index--){
cur = cur->next;
}
temp->next = cur->next;
cur->next = temp;
size++;
}
void deleteAtIndex(int index) {
if (index > (size-1) || index < 0) {
return;
}
linkNode* cur = dummyNode;
while(index--){
cur = cur->next;
}
linkNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
size--;
}
// 打印链表
/*void printLinkedList() {
linkNode* cur = dummyNode;
while (cur->next != nullptr) {
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}*/
private:
int size;
linkNode* dummyNode;
};
四、206.反转链表
1.题目
2.解决思路
图形结合+双指针,注意:赋值的顺序问题
递归法:递归三要素:返回值和形参列表,终止条件,单层递归逻辑
//双指针法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* temp;
ListNode* pre = nullptr;
while(cur != nullptr){
temp = cur->next;
cur -> next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
//递归法
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){//返回值和形参列表
if(cur == NULL) return pre;//终止条件
//单层递归逻辑
ListNode* temp = cur->next;
cur->next = pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
return reverse(NULL, head);
}
};
总结
打卡第三天,在编写代码时要多画图,理清思路,在确定边界时可举特例验证,并且对一些特殊情况要多加靠考虑,如if和while+判断条件的使用,一次性与多次性的问题,以及是否越界问题。