0

I try to use the CreateRoom function to adding new nodes.
Each time I add a node, I edit the old "lastRoom.next" and make it the current new node's address.

And then I make the current new node's pointer as the new "lastRoom"
I thought this is a good idea and I don't need to return anything. I thought this is good.
However, it doesn't work at all.

I'm really bad at coding and I just learn C. Can anyone help?

struct Room {
    int number;
    int status;
    int luxury;
    char occupier[20];
    struct Room *next;
};
//I main copy this kind of code from my lecture notes.
//But It's really crappy. This is the only example I can get from the lecture notes
typedef struct Room Room_t;
Room_t *newRoomNode, *ptr, *prev, *temp;
Room_t *firstRoom = NULL, *lastRoom = NULL;

Room_t* CreateRoom(Room_t **first, Room_t **last, int RoomNumber, int type){
    Room_t *new = (Room_t *)malloc(sizeof(Room_t));
    int *temp;
    if (new == NULL)
    {
        printf("\nMemory was not allocated");
        return 0;
    }
    else
    {
//And then I try my way of adding new nodes. 
//I don't really understand the example so I make my own
        if (*last != NULL)
        {
            (**last).next = new;
        }
        new->number = RoomNumber;
        new->luxury = type;
        new->next = NULL;
        *last = new;
        if (*first=NULL){
            *first=new;
        }
    }
    return 0;
}

void main(){
    CreateRoom(&firstRoom, &lastRoom,1,1);
    printf("%d",(*firstRoom).number);
}
Tsz Fung Li
  • 57
  • 1
  • 1
  • 9

2 Answers2

1
if (*first=NULL){
            *first=new;
}

= is assignment operator. You should use == for comparison.

niyasc
  • 4,440
  • 1
  • 23
  • 50
0

You shouldn't really bother about the last element. (If you need to traverse the list backward, you have to have a prev member in addition to next.) Now, if you want CreateRoom() to always add a new element at the end of the list, it should first traverse the whole list until it reaches the end of it —which it recognizes because of the NULL pointer— and then assign the new pointer to the place it has reached:

while (*first != NULL)
    first = &(*first)->next;
new->number = RoomNumber;
new->luxury = type;
new->next = *first;
*first = new;

Two points are worth being noted:

  1. The assignment *first = new doesn't know if first is firstRoom or the next member of an actual element.
  2. The while loop can be omitted to have new elements inserted at the beginning, or modified so as to have elements sorted the way you want.
Ale
  • 887
  • 10
  • 14