文章:http://blog.csdn.net/lionpku/article/details/44278803 的链表版本。
代码如下:
#include <iostream>
using namespace std;
//敌舰结构体
struct EnemySpaceShip
{
int x_coordinate;
int y_coordinate;
int weapon_power;
EnemySpaceShip* p_next_enemy;
};
//生产敌舰
EnemySpaceShip* addNewEnemyToList(EnemySpaceShip* p_list)
{
EnemySpaceShip* p_ship = new EnemySpaceShip;
p_ship->x_coordinate = 0;
p_ship->y_coordinate = 0;
p_ship->weapon_power = 10;
p_ship->p_next_enemy = p_list;
return p_ship;
}
//升级敌舰
void upgradeWeapons(EnemySpaceShip* p_ship)
{
p_ship->weapon_power += 10;
}
int main()
{
EnemySpaceShip* p_list = NULL;
for (int i = 0; i < 5; i++)
{
p_list = addNewEnemyToList(p_list);
}
cout << "Enemy Space Ships have been built!" << endl;
EnemySpaceShip* p_current = p_list;
int count = 1;
while (p_current != NULL)
{
cout << "EnemySpaceShip[" << count++ << "]: (" << p_current->x_coordinate << "," << p_current->y_coordinate << ") weapon_power: " << p_current->weapon_power << endl;
p_current = p_current->p_next_enemy;
}
cout << "----------UPGRADE WEAPONS----------" << endl;
count = 1;
p_current = p_list;
while (p_current != NULL)
{
upgradeWeapons(p_current);
p_current = p_current->p_next_enemy;
}
count = 1;
p_current = p_list;
while (p_current != NULL)
{
cout << "EnemySpaceShip[" << count++ << "]: (" << p_current->x_coordinate << "," << p_current->y_coordinate << ") weapon_power: " << p_current->weapon_power << endl;
p_current = p_current->p_next_enemy;
}
return 0;
}
(1)当需要通过索引以常量时间访问元素,且预先知道需要存储多少元素,或当需要尽量减少每个元素所占用的空间时,建议使用数组。
(2)当需要能够不断增加新元素,或需要在列表的中间做大量的插入时,建议使用链表。
以上文字摘自《C++程序设计——现代方法》,此书读着很愉快。