链表有有头链表和无头链表
无头链表:所有的节点都包含了有效数据。
有头链表:用一个固定的头节点来指代整个链表,所有的对象挂在这个头节点下面,而头节点本身不包含有效数据。
今天学习在有头链表下插入节点,插入节点的方式有从头部插入和从尾部插入,从头部插入思路就是将头部的节点地址复制给插入数据的节点地址,然后将头部节点地址指向插入数据的地址。
程序实现方法:
#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);
}
|