简单静态链表与简单动态链表

// 链表.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include
#include
#define len sizeof(struct student)
struct student {
char num[10];
int score;
struct student *next;
};
//universal,head为链表表头,p任意调用,测试的指针
struct student *head, *p;


//1,stationary chain table,静态链表中三个表
struct student a, b, c;
//2,dynamic linked table,动态链表中用于暂时替代p位置
struct student * position;






int main()
{//1,stationary chain table
struct student* Creat_Stationary_ChainTable();
struct student * Show_ChainTable(struct student *head);
//2,dynamic linked list
struct student *creat_dynamic_linked_list();




Show_ChainTable(Creat_Stationary_ChainTable());
Show_ChainTable(creat_dynamic_linked_list());
system("pause");
return 0;
}
struct student* Creat_Stationary_ChainTable() {


strcpy(a.num, "1");
strcpy(b.num, "2");
strcpy(c.num, "3");
a.score = 1;
b.score = 2;
c.score = 3;
head = &a;
a.next = &b;
b.next = &c;
c.next = '\0';
return head;


}


struct student * Show_ChainTable(struct student *head) {


p = head;
while (p != '\0') {
printf("%s %d\n", p->num, p->score);
p = p->next;
}
printf("\n\n");
return 0;


}
/*在动态链表中
struct student * p指针用于不断建立新链表,总是第一个指向一个新申请的链表空间
struct student * position 用于建立连接顺序
*/
struct student *creat_dynamic_linked_list() {


int countTable = 0;
position = p = (struct student *)malloc(len);//申请一片len大的空间,p和position都指向他
printf("please input NO.1 table with num,score\n"
"format:num score\n");
scanf("%s", &p->num); getchar();//赋值到p指向的空间
scanf("%d", &p->score); getchar();
head = '\0';
while (p->num[0] != '0')
{
countTable++;
if (countTable == 1)//第一个为头指针
{
head = p;//head指向p空间
p->next = '\0';//定义p->next为空,且此后一直为空
}
else
{
position->next = p;//使得前一个链表尾指向新p空间,如 链表1->next指向链表2,此句缺失则链表断裂,数据遗失


}
position = p;          //position指向p空间,不影响p->next即当行减去三行那一行
p = (struct student *)malloc(len);//p改变位置,指向一个新空间,原本position替代了p位置,类似两个数字换位置时候temp变量,
 //p->next被赋值,不再空,且这个值固定
printf("please input NO.%2d table with num,score\n"
"format:num score\n", countTable + 1);
scanf("%s", &p->num); getchar();
scanf("%d", &p->score); getchar();
}
position->next = '\0';//这里改变position->位置为空,以上p->next在malloc后固定指向oxcdcdcdcd,原本position->next指向p(新p空间,存储了num=0的数据)
 /*由于链表顺着position,必须position->next为空,
 否则最后循环position指向p(新p空间,存储了num=0的数据)然后p->next(固定指向oxcdcdcdcd
 隐去此句显示权限冲突,应该是系统定义的专门空间)*/
return head;
}

你可能感兴趣的:(C,应用,控制台)