c学习笔记--5 结构体实现动态链表

这里不得不多说一句,对于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();
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值