某平台具有强红包功能,请编写程序求收到红包数中有红包大于红包数一半的红包。
分析:这道题目看似简单,其实仔细分析会发现,这道题目其实考察如何将内存有效分配,做到"拿多少用多少"的目的。这里使用链表进行内存的分配与管理。
a.使用C语言来实现
#include<stdio.h>
#include<stdlib.h>
typedef struct red_packet
{
float data;//红包大小
struct red_packet* next;//红包后继结点指针
}readpacket; //定义红包数据类型
readpacket *CreateLinkList()//在表尾生成单链表
{
readpacket *head,*p,*q;
float x;
head=(readpacket*)malloc(sizeof(readpacket));//生成头结点
head->next=NULL;//初始化链表
p=head;
q=p;//q始终指向链尾
printf("Input redpacket:\n");//请输入红包大小
scanf("%f",&x);
while(x!=0)//生成链表其他结点(遇到0结束)
{
p=(readpacket*)malloc(sizeof(readpacket));
p->data=x;//把x给待插入结点*p
p->next=NULL;//把链尾结点后继指针为空
q->next=p;//在链尾插入*p结点
q=p;//q继续指向新的链尾结点*p
scanf("%f",&x);//继续输入数据
}
return head;
}
int Length_LinkList(readpacket *head)//求单链表的长度
{
readpacket *p=head;
int i=0;
while(p->next!=NULL)
{
p=p->next;
i++;
}
return i;
}
void print(readpacket *h)//打印链表
{
readpacket *p;
p=h->next;
while(p!=NULL)
{
printf("%.2f->",p->data);
p=p->next;
}
printf("\n");
}
readpacket *search(readpacket *head,readpacket **sort)//创建"红包大于红包数的一半"的sort链表
{
readpacket *p,*q,*h;
*sort=(readpacket*)malloc(sizeof(readpacket));//生成头结点
(*sort)->next=NULL;//初始化链表
p=*sort;
q=p;//q始终指向链尾
h=head->next;
while(h!=NULL)
{
if(h->data>Length_LinkList(head)/2)
{
p=(readpacket*)malloc(sizeof(readpacket));
p->data=h->data;//把h->data给待插入结点*p
p->next=NULL;//把链尾结点后继指针为空
q->next=p;//在链尾插入*p结点
q=p;//q继续指向新的链尾结点*p
}
h=h->next;
}
return *sort;
}
void main()
{
readpacket *h,**sort,*resort;
int i;
sort=(readpacket**)malloc(sizeof(readpacket));//生成头结点指针
h=CreateLinkList();
printf("输出获得红包:\n");
print(h);//输出红包单链表
i=Length_LinkList(h);//获取红包数目
printf("红包数目为:%d个\n",i);//输出红包数目
resort=search(h,sort);//创建"红包大于红包数的一半"的sort链表
printf("输出红包大于红包数一半的链表:\n");
print(resort);//输出"红包大于红包数的一半"的sort链表
}
b.使用STL模板同样可以实现
#include<list>
#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
void print(list<float> redpacket)//打印链表并完成清理工作
{
int length=redpacket.size();
for(int i=0;i<length;++i)
{
cout<<*redpacket.begin()<<setprecision(3)<<"->";//保留三位有效数字,大数用科学计数表示
redpacket.pop_front();
}
cout<<endl;
}
void main()
{
float money;
list<float> redpacket;
list<float> redpacket_search;
list<float>::iterator ite;
cin>>money;
while(money!=0)
{
redpacket.push_back(money);//红包从尾部插入链表
cin>>money;
}
cout<<"输出红包个数:"<<redpacket.size()<<endl;
for(ite=redpacket.begin();ite!=redpacket.end();ite++)
{
if(*ite>(redpacket.size()/2))
redpacket_search.push_back(*ite);
}
cout<<"输出获得红包链表:"<<endl;
print(redpacket);//输出红包链表后并完成清理工作
cout<<"输出红包大于数目一般的链表:"<<endl;
print(redpacket_search);//输出相应查找链表,并完成对应清理工作
}