使用函数在链接列表中添加节点

时间:2015-04-08 06:09:10

标签: c pointers linked-list runtime-error

我尝试使用CreateRoom功能添加新节点 每次添加节点时,我都会编辑旧的" lastRoom.next"并使其成为当前新节点的地址。

然后我将当前新节点的指针设为新的" lastRoom"
我认为这是一个好主意,我不需要退货。我觉得这很好。
但是,它根本不起作用。

我在编码时非常糟糕,我只是学习C.有人可以帮忙吗?

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);
}

2 个答案:

答案 0 :(得分:1)

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

=是赋值运算符。您应该使用==进行比较。

答案 1 :(得分:0)

你不应该为最后一个元素而烦恼。 (如果您需要向后遍历列表,除了prev之外,您还必须拥有next成员。)现在,如果您希望CreateRoom()始终在末尾添加新元素对于列表,它应首先遍历整个列表,直到它到达它的末尾 - 由于NULL指针它识别它 - 然后将new指针指向它已到达的位置:

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

有两点值得注意:

  1. 作业*first = new不知道第一个是firstRoom还是实际元素的next成员。
  2. 可以省略while循环以在开头插入新元素,或者修改它以便按照您想要的方式对元素进行排序。