数据结构——堆栈

该代码示例展示了如何在C语言中动态分配内存创建结构体数组,输入汽车信息,使用冒泡排序按价格对汽车进行排序,然后输出排序后的结果,最后释放内存空间。主要函数包括创建结构体数组、输入数据、冒泡排序和输出显示。
摘要由CSDN通过智能技术生成

  1. 调用函数在堆区申请空间
  2. 调用函数实现输入
  3. 调用函数对价格排序

思路:类比冒泡排序

注意点:

  1. if(条件) 条件是价格的比较 (p+j)—>price (p+j+1)—>price
  2. 交换的是整个车的信息

例: (p+j)表示整个车的地址

        *(p+j)表示整个车的信息

交换的是*(p+j) 和*(p+j+1) 对应的整体信息

  1.  注意中间变量t的类型,应该是结构体类型
  2. 调用函数输出
  3. 释放堆区空间

头文件

#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<stdlib.h>
struct car
{
	char name[20];
	char color[20];
	float price;

};
struct car *create(int n);
void output(struct car *p,int n);
void input(struct car *p,int n);
void bubble(struct car *p,int n);
#endif


 

//功能函数

#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<stdlib.h>
struct car
{
	char name[20];
	char color[20];
	float price;

};
struct car *create(int n);
void output(struct car *p,int n);
void input(struct car *p,int n);
void bubble(struct car *p,int n);
#endif
ubuntu@ubuntu:~/ubuntu/struct/day_1$ cat test.c
#include"head.h"
struct car *create(int n)
{
	struct car *p=(struct car*)malloc(sizeof(struct car)*n);
	if(NULL==p)
		return NULL;
	else
	{
		return p;
	}

}
//输入条件
void input(struct car *p,int n)
{
	for(int i=0;i<n;i++)
	{
		printf("输入品牌:");
		scanf("%s",(p+i)->name);
		printf("输入颜色:");
		scanf("%s",(p+i)->color);
		printf("输入价格");
		scanf("%f",&(p+i)->price);

	}
}
//排序
void bubble(struct car *p,int n)
{
	int i,j,count;
	struct car temp;
	for(i=0;i<n-1;i++)
	{
		count=0;
		for(j=0;j<n-i-1;j++)
		{
			if((p+j)->price<(p+j+1)->price)
			{
				temp=*(p+j);
				*(p+j)=*(p+j+1);
				*(p+j+1)=temp;
			}
		}
	}
}
//循环输出
void output(struct car *p,int n)
{
	for(int i=0;i<n;i++)
	{
		printf("品牌 %s 颜色 %s 价格 %f\n",(*(p+i)).name,(*(p+i)).color,(*(p+i)).price);
	}
}
ubuntu@ubunt

主函数

#include"head.h"

int main(int argc, const char *argv[])
{
	int n=5;
	struct car *p=create(n);
	input(p,n);//输入条件
	output(p,n);//循环输出
	bubble(p,n);//排序
	output(p,n);
	free(p);//释放堆区空间
	p=NULL;//防止野指针
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值