C++ new和delete操作符

const指针 防止指针指向的内容被修改

#include<iostream>
#include<string>
using namespace std;

struct Elephant{
	string name;
	Elephant* next;
};

void print_elephants(const Elephant* ptr);
Elephant* get_elephants();
void free_list(const Elephant* ptr);

int main()
{
	Elephant* start;
	start = get_elephants();
	print_elephants(start);
	free_list(start);
	return 0;
}

Elephant* get_elephants(){
	Elephant *current, *first;
	int response;
	current=first=new Elephant;
	cout<<"\nName: ";
	cin>>current->name;
	cout<<endl<<"add? 1=Yes 0=No"<<endl;
	cin>>response;
	while(response == 1)
	{
		current = current->next = new Elephant;
		cout<<"\nName: ";
		cin>>current->name;
		cout<<endl<<"add? 1=Yes 0=No"<<endl;
		cin>>response;
	}
	current->next = 0;
	return first;
}

void print_elephants(const Elephant* ptr)
{

	while(ptr)
	{
		cout<<ptr->name<<endl;
		ptr = ptr->next;
	}
}

void free_list(const Elephant* ptr)
{
	const Elephant* temp_ptr;
	while(ptr)
	{
		temp_ptr = ptr->next;
		delete ptr;
		ptr= temp_ptr;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值