记一点笔记
算法笔记 第7章 提高篇(1)——数据结构专题(1)
7.1 栈的应用
7.2 队列的应用
7.3 链表处理
- 以下采用带头结点的写法
7.3.1 链表的概念
struct node {
typename data;
node* next;
};
7.3.2 使用malloc函数或new运算符为链表结点分配内存空间
1. malloc函数
- C语言
stdlib.h
头文件下用于申请动态内存的函数,其返回类型是申请的同变量类型的指针。申请成功,返回指向这块空间的指针;申请失败,返回NULL。
typename* p = (typename*)malloc(sizeof(typename));
2. new运算符
- c++中用来申请动态空间的运算符,其返回类型是申请的同变量类型的指针。申请成功,返回指向这块空间的指针;申请失败,启动c++异常机制处理而不是返回NULL。
typename* p = new typename;
3. 内存泄漏
- 在使用完
malloc
与new
开辟出来的空间后必须将其释放,否则会造成内存泄漏
(1) free函数
- 对应
malloc
函数,同样是stdlib.h
头文件下。释放指针所指的内存空间,将指针变量指向NULL。
free(p); //p为需要释放的内存空间的指针变量
(2) delete运算符
- 对应
new
运算符。
delete(p); //p为需要释放的内存空间的指针变量
7.3.3 链表的基本操作
1. 创建链表
//尾插法
node* create(int Array[], int n) {
node *p, *tail, *head;
head = new node;
head->next = NULL;
tail = head;
for(int i = 0; i < n; i++) {
p = new node;
p->data = Array[i];
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
2. 查找元素
//返回元素个数
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;
}
3. 插入元素
void insert(node *head, int pos, int x) {
node *p = head;
for(int i = 0; i < pos; i++) {
p = p->next;
}
node *q = new node;
q->data = x;
q->next = p->next;
p->next = q;
}
4. 删除元素
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;
}
}
}
7.3.4 静态链表
struct Node {
typename data;
int next;
} node[size];
- 使用静态链表时,尽量不要把结构体类型名和结构体变量名取成相同的名字。