c學習筆記--5 結構體實現動態連結串列
阿新 • • 發佈:2018-12-12
這裡不得不多說一句,對於c來說指標我認為最好用的就是連結串列,有很多實用的地方
#include<string.h>
#include<stdio.h>
//C語言 連結串列篇
//結構體實現單向連結串列
struct MyStruct
{
char name[20];
struct MyStruct *before;
};
void test6()
{
int a = 0;
//原理演示
//連結串列頭 作為一個空結構體 表示找到頭了 結束回溯
static struct MyStruct *list_head = NULL;
struct MyStruct mt = {"songyu",list_head};
struct MyStruct mt2 = { "zhanghaimi",&mt};
struct MyStruct mt3 = { "xuqiu",&mt2 };
struct MyStruct temp = mt3;
while (temp.before != NULL)
{
printf("before name is:%s\n", temp.name);
temp = *temp.before;
}
//動態申請 新增連結串列
struct MyStruct *tempp = NULL;
int j = 0;
char inputname[20];
const char exist[] = "ok";
typedef struct MyStruct MS; //重新命名,便於書寫,太長了struct node
typedef struct MyStruct* MSPoint;
MSPoint head = NULL;//head指向NULL 防止野指標
MSPoint temp1;
while (j < 3)
{
MSPoint p = (MSPoint)malloc(sizeof(MS)); //malloc()函式分配Node大小的空間,型別轉換為Link型,指賦給p
if (p == NULL)//空間分配失敗
{
printf("malloc error!\n");
exit(-1); //結束程序 檔案包含stdlib.h
}
printf("請輸入姓名:");
scanf("%s", &inputname);
if (strcmp(inputname, exist)==0)
{
break;
}
strcpy(p->name, &inputname);
if (j == 0)
{
p->before = head;
}
else
{
p->before = temp1;
}
temp1 = p;
j++;
}
//定義結構體指標,訪問成員時就用->
//定義結構體變數,訪問成員時就用.
for (j=3; j > 0; j--)
{
printf("now value is :%s before address is :%d \n", temp1->name, temp1->before);
temp1 = temp1->before;
}
//使用malloc方法 申請固定記憶體 動態新增連結串列元素
gets();
gets();
}