203.移出链表元素
思路详解:首先,想要移出链表元素,至少要有两个指针,一个指向删除元素,一个指向删除元素的前一个元素,在这个代码中,我设置虚拟头节点的目的是为了让删除节点的操作都是统一的,因为如果是删除头节点的话,需要将头节点向后移动一位,而删除其他节点的话,需要通过前一个节点来移出元素。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy=new ListNode;
dummy->next=head;
ListNode* pur=dummy;
ListNode* cur=head;
while(cur!=nullptr){
if(cur->val==val){
pur->next=pur->next->next;
cur=pur->next;
}else{
cur=cur->next;
pur=pur->next;
}
}return dummy->next;
}
};
707.设计链表
个人感觉是考察链表操作比较细致的一道题了,基本操作都覆盖到了,要注意几个点:
1.定义虚拟节点要是这个类的成员变量,若定义在这个类的构造函数的话,那么这个虚拟头节点就不是全局的变量了,并且在每次创建实例时都会创建出来一个虚拟头节点,这样会导致内存泄露。
2.这道题我犯了一个错误,就是在添加头节点函数,要用dummy进行操作
class MyLinkedList {
public:
struct List{
int val;
List* next;
List(int val):val(val),next(nullptr){}
};
int size;
List* dummy;
MyLinkedList() {
size=0;
dummy=new List(0);
}
int get(int index) {
if(index>(size-1)||index<0){
return -1;
}
List* cur=dummy->next;
while(index--){
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
List* newnode=new List(val);
newnode->next=dummy->next;
dummy->next=newnode;
size++;
}
void addAtTail(int val) {
List* newnode=new List(val);
List* cur=dummy;
while(cur->next!=nullptr){
cur=cur->next;
}
cur->next=newnode;
size++;
}
void addAtIndex(int index, int val) {
if(index>size||index<0){
return ;
}
List* newnode=new List(val);
List* cur=dummy;
while(index--){
cur=cur->next;
}
newnode->next=cur->next;
cur->next=newnode;
size++;
}
void deleteAtIndex(int index) {
if(index>=size||index<0){
return ;
}
List* cur=dummy;
while(index--){
cur=cur->next;
}
List* node=cur->next;
cur->next=cur->next->next;
delete node;
node=nullptr;
size--;
}
};
206.反转链表
1.经典双指针问题,需要注意的是在每次循环起始,要存一下快指针的下一个元素的地址,防止丢失。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* left=nullptr;
ListNode* right=head;
while(right!=nullptr){
ListNode* node=right->next;
right->next=left;
left=right;
right=node;
}
head=left;
return head;
}
};