算法笔记 第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. 内存泄漏

  • 在使用完mallocnew开辟出来的空间后必须将其释放,否则会造成内存泄漏
(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];
  • 使用静态链表时,尽量不要把结构体类型名和结构体变量名取成相同的名字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值