一些概念
· 线性表可分为顺序表和链表,其中顺序表可简单理解为数组。
· 数组为一块连续的地址空间,而链表则是由若干个节点组成(每个节点表示一个元素),且结点在内存中的存储位置通常是不连续的。
· 链表的两个节点之间一般通过一个指针来从一个结点指向另一个结点
· 链表的结点由两部分构成,即数据域和指针域
struct node{
typename data;
node* next;
};
· 链表又可分为带头结点(head)的链表和不带头结点的链表。
使用malloc函数或new运算符为链表结点分配内存空间
malloc函数
C语言stdlib.h头文件下的
……
new运算符(这个好用)
例
int* p=new int;
node* p=new node;
……
内存泄露
1.free函数
对应malloc函数
……
2.delete函数
对应new运算符
一般考试中,不写也没事……
链表的基本操作
创建链表
struct node{
int data;
node* next;
};
node* create(int Array[]){
node *p,*pre,*head; //pre保存当前结点的前驱结点,head为头结点
head=new node; //创建头结点
head->next=NULL; //头节点不需要数据域,指针域初始为NULL
pre=head;
for(int i=0;i<n;i++){
p=new node;
p->data=Array[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head; //返回头结点
}
查找元素
//在以head为头结点的链表上计数元素x的个数
int search(node* head,int x){
int count=0;
node *p=head->next;
while(p!=NULL){
if(p->data==x) count++;
p=p->next;
}
return count;
}
插入元素
//将x插入以head为头结点的链表的第pos个位置上
void insert(node* head,int pos,int x){
node* p=head;
for(int i=0;i<pos-1;i++){
p=p->next;
}
node* q=new node;
q->data=x;
q->next=p->next;
p->next=q;
}
删除元素
//删除以head为头结点的链表中所有数据域为x的结点
void del(node* head,int x){
node* p=head->next;
node* pre=head;
while(p!=NULL){
if(p->data==x){
pre->next=p->next;
delete(p);
p=pre->next;
}else{
pre=p;
p=p->next;
}
}
}