시도한 바를 수행하는 더 좋은 방법이 있다는 것을 알고 있지만 내가 C++을 배우기 위해 사용하고있는 책이며, 내가 계속 진행하기 전에 몇 가지 기본 사항을 이해하는 데 도움이 될 것입니다. 내가 프로그램을 테스트하기 위해 임의의 값을 사용하고링크 된 목록의 구조체를 삭제하는 함수를 구현하려고 시도하기 전에 구조체를 지정하기 전에 구조체를 지정하는 중
#include <iostream>
using namespace std;
struct EnemySpaceShip
{
int weapon_power;
int xcoord;
int ycoord;
EnemySpaceShip *nextEnemy;
};
EnemySpaceShip* getNewEnemy(EnemySpaceShip* p_enemies) // Creates a new EnemySpaceShip in linked list p_enemies
{
EnemySpaceShip *p_ship = new EnemySpaceShip;
p_ship->xcoord = 0;
p_ship->ycoord = 0;
p_ship->weapon_power = 10;
p_ship->nextEnemy = p_enemies;
p_enemies = p_ship;
return p_ship;
}
EnemySpaceShip* findPreRemove(EnemySpaceShip* p_enemies, int x_attack, int y_attack) // finds the element that is before the ship to be removed or returns NULL
{
EnemySpaceShip *p_current = p_enemies;
EnemySpaceShip *initialShip = p_enemies;
int i= 0;
while (p_current != NULL)
{
i++;
if (p_current->xcoord == x_attack && p_current->ycoord == y_attack)
{
if (i == 1)
{
delete initialShip;
delete p_current;
return NULL;
}
else
{
for (int j = 1; j < i - 1; j++)
{
initialShip = initialShip->nextEnemy;
}
delete p_current;
return initialShip;
}
}
p_current = p_current->nextEnemy;
}
return NULL;
}
EnemySpaceShip* findRemove(EnemySpaceShip* p_enemies, int x_attack, int y_attack)
{
EnemySpaceShip *p_current = p_enemies;
while (p_current != NULL)
{
if (p_current->xcoord == x_attack && p_current->ycoord == y_attack)
{
return p_current;
}
p_current = p_current->nextEnemy;
}
}
EnemySpaceShip* removeEnemyShip(EnemySpaceShip *p_ship) // deletes the ship parameter and returns the ship after it in the list
{
EnemySpaceShip *enemyAfterRemove = new EnemySpaceShip;
enemyAfterRemove = p_ship->nextEnemy;
delete p_ship;
return enemyAfterRemove;
}
int main()
{
EnemySpaceShip *p_enemies = NULL;
EnemySpaceShip *Ship1 = getNewEnemy(p_enemies);
EnemySpaceShip *Ship2 = getNewEnemy(p_enemies);
EnemySpaceShip *Ship3 = getNewEnemy(p_enemies);
Ship3->xcoord = 5; //arbitrary numbers to test the code
Ship3->ycoord = 5;
EnemySpaceShip *ShipBeforeRemove = findPreRemove(p_enemies, 5, 5);
EnemySpaceShip *ShipToRemove = findRemove(p_enemies, 5, 5);
ShipBeforeRemove->nextEnemy = removeEnemyShip(ShipToRemove);
}
, 나는 완전히 분명히에 사용되는 것이 게임의 기능으로이를 구현 할 필요가 없습니다 : 어쨌든, 여기 내 코드입니다. 어떤 도움이라도 대단히 감사합니다. 나는 다음과 같은 희망
그래서, – superM
귀하의 구조는 앞으로 점) 질문을 얻을 수 없다 'before this one'-'p_last'와 같은 포인터를 유지하십시오. 양방향 (전후 포인터)으로 만들지 않으면 이전 컨텍스트가없는 요소를 삭제할 수 없습니다. – Greyson