6.3w+
社区成员
//编译,运行没有问题;
#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 << "\nAdd another? (1 == yes, 0 == no): ";
cin >> response;
while ( response == 1 )
{
current = current -> next = new Elephant;
cout << "\nNAME: ";
cin >> current -> name;
cout << "\nAdd another? (1 == yes, 0 == no): ";
cin >> response;
}
current -> next = 0;
return first;
}
void print_elephants( const Elephant* ptr )//打印
{
int count = 1;
cout << "\n\n\n";
while ( ptr != 0 ) {
cout << "Elephant number " << count++
<< " is " << ptr -> name << '\n';
ptr = ptr -> next;
}
}
void free_list( const Elephant* ptr )//释放
{
const Elephant* temp_ptr;
while ( ptr != 0 )
{
cout <<"1111111111111111" <<endl;
temp_ptr = ptr -> next;
delete ptr;
ptr = temp_ptr;
}
}