I'm relatively new to programming in c and I'm working on a complex project for one of my classes. I need to know if my definition of my function insertAfter works as intended and if I'm using it correctly.
void SeatNode::insertAfter(SeatNode* node)
{
// insert this->SeatNode after node
this->next_node = node->next_node;
node->next_node = this->next_node;
}
void Compact::createSeatReservation(Passenger p)
{
SeatNode seat(p);
seat.insertAfter(this->driver_seat.getNextNode());
}
If it works as intended Compact::createSeatReservation(Passenger p) should create a SeatNode object called seat and it should insert seat after a SeatNode object called driver_seat. Forming a linked list with driver_seat as the head node and seat as the next node after driver_seat. As I said I'm relatively new to c any help will be appreciated.
CodePudding user response:
No, it doesn't. I'll go through it step by step starting at the point you call insertAfter():
- You change the next pointer of the seat to the one after the driver, so far so good.
- You change the next pointer of the driver to the next pointer of the seat which is the pointer that you just changed to the one after the driver in step 1, so this assignment doesn't change anything.
What you want to do in your second assignment is to change the next pointer of the driver to the newly inserted seat, which you can do this way:
node->next_node = this;
There's also a problem inside the createSeatReservation() method: When you call insertAfter() with the node after the driver the new seat will be inserted after the seat that itself is after the driver. Here the correct line would be:
seat.insertAfter(this->driver_seat);
So the complete correct code would be
void SeatNode::insertAfter(SeatNode* node)
{
// insert this->SeatNode after node
this->next_node = node->next_node;
node->next_node = this;
}
void Compact::createSeatReservation(Passenger p)
{
SeatNode seat(p);
seat.insertAfter(this->driver_seat);
}