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;
}