链表相关知识整理

定义

链表是一种物理存储单元非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。

优点:

  1. 插入,删除,不需移动其他元素, 只需改变指针。
  2. 链表各个节点在内存中空间不要求连续!空间利用率高,数组的存储空间连续,内存空间利用率低。

缺点

  1. 访问其中的元素效率低。
    例如:访问第100个元素,必须从头节一直next 99次 才能访问到。

数组
在这里插入图片描述
链表
在这里插入图片描述

基本操作

  1. 插入
  2. 删除
  3. 查找

插入

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值