Article: http://blog.csdn.net/lionpku/article/details/44278803 's linked list version.
The code is as follows:
#include <iostream> using namespace std;
The warship structure body struct enemyspaceship {int x_coordinate;
int y_coordinate;
int weapon_power;
enemyspaceship* P_next_enemy;
};
Production of enemy ships 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;
//upgrade enemy 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_c Oordinate << ", << 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_c Oordinate << ", << p_current->y_coordinate <<") Weapon_power: "<< p_current->weapon_
Power << Endl;
P_current = p_current->p_next_enemy;
return 0; }
The rule of thumb for the selection of linked list and array:
(1) It is recommended to use an array when you need to access the elements through the index in constant time and know in advance how many elements you need to store, or when you need to minimize the space occupied by each element.
(2) When you need to be able to constantly add new elements, or need to do a large number of inserts in the middle of the list, it is recommended to use the linked list.
The above text is excerpted from "C + + program Design--Modern Method", this book reads very happily.