C语言复习-链表

链表:


特点:

通过 next 指针 把内存上不连续 的几段数据 联系起来

set nu -- 打印行号

概念: 一种数据结构 -- 数据存放的思想

比如 -- 数组 -- 内存连续的一段空间,存放相同类型的一堆数据
缺点 -- 增删元素很 难  -- 不灵活 --> 引入链表

 next指针的初步认识:


#include<stdio.h>

struct chain
{
int num;
struct chain* next;
};


int main()
{
int arr[3]={1,2,3};
puts("use arr to output:");

for(int i=0;i<3;++i)
{
printf("%d ",arr[i]);
}
puts("");
struct chain a={1,NULL};
struct chain b={2,NULL};
struct chain c={3,NULL};

a.next=&b;
b.next=&c;
puts("use chain to output:");
printf("%d %d %d\n",a.num,a.next->num,b.next->num);

return 0;
}


遍历:


遍历条件 -- 尾部元素的next 指针为NULL -- 结束条件

遍历 只需要 传入首元素的地址就-ok -> 后续元素直接 next去获取


#include<stdio.h>

struct chain
{
int num;
struct chain* next;
};


void printChain(struct chain* head)
{
struct chain* p=head;
while(p!=NULL)
 {
 printf("%d ",p->num);
 p=p->next;
 }

puts("");
}


int main()
{
int arr[3]={1,2,3};
puts("use arr to output:");

for(int i=0;i<3;++i)
{
printf("%d ",arr[i]);
}
puts("");
struct chain a={1,NULL};
struct chain b={2,NULL};
struct chain c={3,NULL};

a.next=&b;
b.next=&c;
puts("use chain to output:");
//printf("%d %d %d\n",a.num,a.next->num,b.next->num);

printChain(&a);


return 0;
}

//p-> next 下一个元素的地址


==========================================

列表的查找

int getTotal(struct chain* head) //获得链表长度
{
int cnt=0;
while(head!=NULL)
{
cnt++;
head=head->next;
}
return  cnt;
}

int  check(struct chain* head,int n) //查看n是否在链表内
{
while(head!=NULL)
{
if(head->num==n) return 1;

head=head->next;
return 0;
}

=================================


插入新节点

后面插入


int  insert(struct chain* head,int data,struct chain*new)
{
    struct chain* p=head;
    while(p!=NULL)
    {
     if(p->num==data) //找到目标元素位置
      {
        new->next=p->next; //插入到目标元素后面
        p->next=new; //目标元

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值