打印
[AT32F421]

C语言链表学习

[复制链接]
215|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
tifmill|  楼主 | 2024-2-27 23:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
链表有有头链表和无头链表
无头链表:所有的节点都包含了有效数据。
有头链表:用一个固定的头节点来指代整个链表,所有的对象挂在这个头节点下面,而头节点本身不包含有效数据。
今天学习在有头链表下插入节点,插入节点的方式有从头部插入和从尾部插入,从头部插入思路就是将头部的节点地址复制给插入数据的节点地址,然后将头部节点地址指向插入数据的地址。

程序实现方法:
#include<stdio.h>
#include <stdlib.h>
  struct  st
{
        int a;
        struct st *next;
};
struct  st d={0};
void add1(struct st* asj );
void add1(struct st * asj )  
{
        asj->next=d.next;
        d.next=asj;        
}
void main()
{
struct  st* obj_1 = (struct  st*)malloc (sizeof(struct  st));
  struct  st* obj_2 = (struct  st*)malloc (sizeof(struct  st));
  obj_1->a=0;
  add1(obj_1);
  printf("d=%d\n",&(d));
  printf("d.a=%d\n",&(d.a));
  printf("d.next=%d\n",&(d.next));
  printf("next=%d\n",d.next);
  printf("obj_1.a=%d\n",&(obj_1->a));
  printf("obj_1.next=%d\n",&(obj_1->next));
  printf("next=%d\n",obj_1->next);
  obj_2->a=0;
  add1(obj_2 );
  printf("obj_2.a=%d\n",&(obj_2->a));
  printf("obj_2.next=%d\n",&(obj_2->next));
  printf("obj_2.next=%d\n",obj_2->next);
}
运行结果为:
C:\Users\sky\AppData\Local\YNote\data\qq521525C35984A5C31E082DDBFE88B641\919e5ac8cd3140c1aa746edd894df2f0\捕获.png
       从结果可以发现obj_1为最后一个节点,而后面插入的数据地址放到了obj_1的前面,而obj_2的节点地址指向了obj_1,这就是从首地址插入的方法。
       从尾部插入的方法是首先遍历下链表找到最后一个元素,让最后元素的节点指向要插入的数据,要插入的数据节点为0;
程序:
#include<stdio.h>
#include <stdlib.h>

  struct  st
{
        int a;
        struct st *next;
};
struct  st d={0};

void add2(struct st * asb );

void add2(struct st * asb )
{
        struct st *p=&d;
        while(p->next)
          p=p->next;
        p->next=asb;
        asb->next=0;

}

void main()
{
  struct  st* obj_1 = (struct  st*)malloc (sizeof(struct  st));
  struct  st* obj_2 = (struct  st*)malloc (sizeof(struct  st));
  obj_1->a=0;
  add2(obj_1);
  printf("d=%d\n",&(d));
  printf("d.a=%d\n",&(d.a));
  printf("d.next=%d\n",&(d.next));
  printf("next=%d\n",d.next);
  printf("obj_1.a=%d\n",&(obj_1->a));
  printf("obj_1.next=%d\n",&(obj_1->next));
  printf("next=%d\n",obj_1->next);
  obj_2->a=0;
  add2(obj_2 );
  printf("obj_2.a=%d\n",&(obj_2->a));
  printf("obj_2.next=%d\n",&(obj_2->next));
  printf("obj_2.next=%d\n",obj_2->next);

}

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

27

主题

1136

帖子

0

粉丝