链表有动态和静态两种
1.动态
动态链表可以带头结点(head)也可以不带,动态的写法要先申请空间
申请空间有2种写法
1)malloc 头文件stdlib.h
int* p=(int*)malloc(sizeof(int));
node* p=(node*)malloc(sizeof(node))`
因为malloc返回的是指针类型,所以还要强制转换
2)new运算符
int* p=new int;
node* p=new node;
new运算符和malloc都可以申请空间,但是也有申请失败的时候,当你申请空间过大的时候就会失败,失败的时候会返回NULL,
内存泄漏
内存泄漏指的是new或malloc后的空间没有释放,就会一直占着内存,在大的程序中就有可能没有空间分配,所以申请完空间后可以释放
malloc ---- free free(p)
new ----delete delete(p)
这两个是成对出现的,```
free和delete主要实现的是释放申请的空间,指针本身依然存在
2.链表的基本操作
创建,查找,插入,删除
#include<iostream>
#include<cstdlib>
using namespace std;
struct node{
int date;
node* next;
};
node* create(int a[]){ //创建链表
node *p,*pre,*head;
head = new node;
head->next = NULL;
pre = head;
for(int i = 0 ;i < 5 ; i++){
p=new node;
p->date =a[i];
p->next =NULL;
pre -> next = p;
pre = p;
}
return head;
}
int search(node* head , int x){//查找
int count = 0;
node* p=head->next;
while(p != NULL){
if(p->date == x) count++;
p=p->next;
}
return count;
}
void insert(node* head , int pos ,int x){//添加
node* p =head;
for(int i=1;i<=pos-1 ;i++){
p=p->next;
}
node* q= new node;
q->date =x;
q->next = p->next ;
p->next = q;
}
void del(node* head , int x){//删除
node* p=head->next;
node* pre=head;
while(p!=NULL){
if(p->date == x){
pre->next = p ->next;
delete(p);
p=pre->next;
}
else{
pre = p;
p = p ->next;
}
}
}
int main(){
int a[5]={1,2,3,4,5};
node* L=create(a);
// L = L->next;
// while(L !=NULL){
// cout<<L->date <<' ';
// L=L->next;
// }
// cout<<search(L,5);
insert(L,3,10);
del(L,10);
L = L->next;
while(L !=NULL){
cout<<L->date <<' ';
L=L->next;
}
return 0;
}
我觉得主要的几个地方
1.第一次使用指针要分配空间,malloc后者new,一般头节点要这样
2.头结点要注意封尾,就是创建完head节点,还要注意head->next=NULL
3.注意逻辑关系,位置,是链表的基础
2.静态
我看PAT经常用的是静态
静态链表的原理值hash,通过建立结构体数组,令数组下标直接表示节点的地址,静态链表不需要头结点
struct Node {
typename data;//数据域
int next //指针域
}node[size];
静态链表基础是这样的,在后面做题的时候在详细的写下
链表操作详解
2598

被折叠的 条评论
为什么被折叠?



