内存细节讨论
- 不要用静态分配的方式设计!!!因为一旦离开该数据的作用范围,它会被自动销毁,而动态分配则完全不同,它由于不会销毁内存,所以只要找到了地址便可以得到该块内存区域的数据。
- 由于是动态分配,动态分配在
C/C++ 中它并不会自动回收,需要手动释放内存,所以最好把析构函数写好。
构造函数和析构函数 以及基本的结构定义
struct listNode{
int val;
listNode* next;
listNode(int v):val(v),next(nullptr){}
};
private: int size;listNode* head;listNode* rear;
public:
MyLinkedList() {
head =new listNode(0);
rear = head;
size = 0;
}
~MyLinkedList(){
listNode* pre = head;
listNode* cur = head->next;
while(cur){
delete pre;
pre = cur;
cur = cur->next;
}
delete pre;
}
头插和尾插的O(1)实现
void addAtHead(int val) {
listNode* q = new listNode(val);
q->next = head->next;
head->next = q;
if(size<1)rear = q;
size++;
}
void addAtTail(int val) {
listNode* t =new listNode(val);
rear->next = t;
rear = rear->next;
size++;
}
插入指定位置实现
void addAtIndex(int index, int val) {
if(index==size){
addAtTail(val);
return;}
else if(index<=0){
addAtHead(val);
return;}
else if(index>size)
return;
else{
listNode* t = new listNode(val);
listNode* q = head;
for(int i=0;i<index;i++){
q = q->next;
}
t->next = q->next;
q->next = t;
}
size++;
}
指定位置删除和得到指定位置的值的实现
void deleteAtIndex(int index) {
if(index<0 or index>size-1)
return;
listNode* p = head;
for(int i=0;i<index;i++){
p = p->next;
}
if(index == size-1)
rear = p;
listNode* t = p->next;
p->next = t->next;
delete t;
size--;
}
int get(int index) {
if(index>size-1 or index<0)
return -1;
listNode* p = head;
for(int i=0;i<=index;i++){
p = p->next;
}
return p->val;
}
汇总代码得到答案
class MyLinkedList {
struct listNode{
int val;
listNode* next;
listNode(int v):val(v),next(nullptr){}
};
private: int size;listNode* head;listNode* rear;
public:
MyLinkedList() {
head =new listNode(0);
rear = head;
size = 0;
}
~MyLinkedList(){
listNode* pre = head;
listNode* cur = head->next;
while(cur){
delete pre;
pre = cur;
cur = cur->next;
}
delete pre;
}
int get(int index) {
if(index>size-1 or index<0)
return -1;
listNode* p = head;
for(int i=0;i<=index;i++){
p = p->next;
}
return p->val;
}
void addAtHead(int val) {
listNode* q = new listNode(val);
q->next = head->next;
head->next = q;
if(size<1)rear = q;
size++;
}
void addAtTail(int val) {
listNode* t =new listNode(val);
rear->next = t;
rear = rear->next;
size++;
}
void addAtIndex(int index, int val) {
if(index==size){
addAtTail(val);
return;}
else if(index<=0){
addAtHead(val);
return;}
else if(index>size)
return;
else{
listNode* t = new listNode(val);
listNode* q = head;
for(int i=0;i<index;i++){
q = q->next;
}
t->next = q->next;
q->next = t;
}
size++;
}
void deleteAtIndex(int index) {
if(index<0 or index>size-1)
return;
listNode* p = head;
for(int i=0;i<index;i++){
p = p->next;
}
if(index == size-1)
rear = p;
listNode* t = p->next;
p->next = t->next;
delete t;
size--;
}
};
|