定义
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
优点:
- 插入,删除,不需移动其他元素, 只需改变指针。
- 链表各个节点在内存中空间不要求连续!空间利用率高,数组的存储空间连续,内存空间利用率低。
缺点
- 访问其中的元素效率低。
例如:访问第100个元素,必须从头节一直next 99次 才能访问到。
数组
链表
基本操作
- 插入
- 删除
- 查找
插入
p = (struct str *)malloc(sizeof(struct str ));
// p = new str; cpp
p -> next = q -> next;
q -> next = p;
删除
p -> next = q -> next;
free(q);
查找
struct str *Search(struct str *head,int x)
{
struct str *p;
p = head -> next;
while(p)
{
if(p -> data == x)
return (p);
else
p = p -> next;
}
return NULL;
}
建表
- 逆序建立链表(头插法)
struct str *head_creat(int n)
{
int i;
struct str *head,*p;
head = (struct str *)malloc(sizeof(struct str ));
head -> next = NULL;
for(i = 1; i <= n; i++)
{
p = (struct str *)malloc(sizeof(struct str ));
scanf("%d",&p->data);
p -> next = head -> next;
head -> next = p;
}
return head;
}
- 顺序建立链表(尾插法)
struct str *tail_creat(int n)
{
int i;
struct str *head,*tail,*p;
head = (struct str *)malloc(sizeof(struct str ));
head -> next = NULL;
tail = head;
for(i = 1; i <= n; i++)
{
p = (struct str *)malloc(sizeof(struct str ));
scanf("%d",&p->data);
p -> next = NULL;
tail -> next = p;
tail = p;
}
return head;
}
链表的逆置
void Reverse(struct str *head)
{
struct str *p,q;
p = head -> next;
q = p -> next;
head -> next = NULL;
while(p)
{
p -> next = head -> next;
head -> next = p;
p = q;
if(q)
q = q -> next;
}
}
链表的销毁
p=head->next;
free(head);
while(p)
{
free(p);
p=p->next;
}