鏈表有有頭鏈表和無頭鏈表
無頭鏈表:所有的節(jié)點都包含了有效數(shù)據(jù)。
有頭鏈表:用一個固定的頭節(jié)點來指代整個鏈表,所有的對象掛在這個頭節(jié)點下面,而頭節(jié)點本身不包含有效數(shù)據(jù)。
今天學習在有頭鏈表下插入節(jié)點,插入節(jié)點的方式有從頭部插入和從尾部插入,從頭部插入思路就是將頭部的節(jié)點地址復制給插入數(shù)據(jù)的節(jié)點地址,然后將頭部節(jié)點地址指向插入數(shù)據(jù)的地址。
0.png (59.21 KB, 下載次數(shù): 140)
下載附件
2017-4-6 01:56 上傳
程序實現(xiàn)方法:
#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
從結果可以發(fā)現(xiàn)obj_1為最后一個節(jié)點,而后面插入的數(shù)據(jù)地址放到了obj_1的前面,而obj_2的節(jié)點地址指向了obj_1,這就是從首地址插入的方法。
從尾部插入的方法是首先遍歷下鏈表找到最后一個元素,讓最后元素的節(jié)點指向要插入的數(shù)據(jù),要插入的數(shù)據(jù)節(jié)點為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);
}
結果為:
0.png (60.34 KB, 下載次數(shù): 136)
下載附件
2017-4-6 01:56 上傳
可見每次插入的數(shù)據(jù)下個節(jié)點總是指向了最后,而他們的內存是連續(xù)的。
鏈表的學習.pdf
(63.45 KB, 下載次數(shù): 25)
2017-4-6 01:56 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|