链表 课程回顾

本文回顾了链表和顺序表的概念。顺序表中逻辑相邻的元素在物理位置上也相邻,查找和修改操作高效,但插入和删除操作需要移动元素,时间复杂度为O(n)。链表则允许逻辑相邻的元素在物理位置上不相邻,擅长利用碎片内存,插入和删除操作时间为O(1),但查找和修改操作较慢,时间复杂度为O(n)。此外,还介绍了链表的基本操作:增、删、改、查。
摘要由CSDN通过智能技术生成

2020.7.27

链表

顺序表 - 逻辑上相邻的元素物理上也相邻
  • 整块分配内存
  • 优点:查找&修改 时间复杂度O(1)
  • 缺点:插入&删除 时间复杂度O(n)
链表 - 逻辑上相邻的元素不一定物理上相邻
  • 可以利用碎片内存
  • 优点:插入&删除 时间复杂度O(1)
  • 缺点:查找&修改 时间复杂度O(n)

用指针模拟链表

struct Node{
	int val;
	Node* next=NULL;
};

void insert(Node* head, int idx, int x)
{
	Node* pos = find(head, idx);
	Node* node = new Node;
	node->val = x;
	node->next = pos->next;
	pos->next = node;
} 

void del(Node* head, int idx)
{
	Node* pos = find(head, idx-1);
	pos->next = pos->next->next;
} 

void edit(Node* head, int idx, int x)
{
	Node* pos = find(head, idx);
	pos->val = x;
}

Node* find(Node* head, int idx)
{
	Node* curr = head;
	for(int i=1;i<=idx;i++)
	{
		curr = curr->next;
	}
	return curr;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值