我正在学习C,而我正试图理解一个更好的链接列表概念。 我有一个代码作为一个例子(我把它改成了我想要更好理解的那个)。 代码没有任何错误,但再次像我说的那样更好地理解它。 请先查看代码,然后在代码下方查看我的问题:
以下是我的struct和我的第一个函数的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct client{
char first_name[20];
char last_name[20];
char id;
char reference;
char deposit;
struct client *next; // pointer to the next entry in the clients list
};
typedef struct client new_Client;
/***********************************************************
* find_Client
* Finds a place in the list to insert new user
* Input: User's first and last name, id, reference, deposit
* Returns: A pointer to teh struct which AFTER we'll insert
the new struct. NULL if head of the linked-list
***********************************************************/
new_Client *find_Client(char *new_last_name, new_Client *head)
{
new_Client *prev = NULL; // previous has nothing
new_Client *curr = head; // current is the head
while (curr != NULL) //// while the current is not NULL because if it's null it's not head
{
if (strcmp(new_last_name, curr->last_name)<0)
break;
prev = curr;
curr = curr->next; // pointing to the next node
}
return prev;
}
这是我的下一个功能,我通常会遇到问题
/***********************************************************
* add_new_Client
* Adds a new client
* Input: clients details and the address of the list's head
* Returns: nothing
***********************************************************/
void add_new_Client(char *first_n, char *last_n, char *ident, char *ref, char *dep, new_Client **head)
{
new_Client *after;
// create new entry
new_Client *new_entry = (new_Client*)malloc(sizeof(new_Client)); //allocating size of the struct
if (NULL == new_entry)
{
exit(1); //Q1: does it mean that it terminates?
}
else
{
strcpy(new_entry->first_name, first_n);
strcpy(new_entry->last_name, last_n);
strcpy(&new_entry->id, ident);
strcpy(&new_entry->reference, ref);
strcpy(&new_entry->deposit, dep);
}
after = find_Client(new_entry->last_name, *head); // Q2: don't understand this line..
if (NULL == after) // new head
{
if (NULL == *head) // Q3: for adding the first item (when the head is NULL) --> why is this condition necessary
{
new_entry->next = NULL;
}
else
{
new_entry->next = *head;
}
*head = new_entry;
}else
{ //add in the middle
new_entry->next = after->next;
after->next = new_entry;
}
}
好的,我把我的问题放在代码中。它们被标记为Q1,Q2和Q3。 如果您希望我在我的帖子上编辑并更改提问方法,请告诉我更方便您理解我的问题。
答案 0 :(得分:4)
//Q1: does it mean that it terminates?
exit(1);
是的,程序将以1 which is interpreted as failure退出。
// Q2: don't understand this line..
after = find_Client(new_entry->last_name, *head);
此处,after
是指向struct new_Client
的指针。函数find_Client
返回指向使用new_entry->last_name
搜索的客户端的指针,并传递head
以便为搜索提供开始,某处开始。
// Q3: for adding the first item (when the head is NULL) --> why is this condition necessary
if (NULL == *head)
因为当列表中只有一个元素时,它就是单独的,也就是说,它没有next
元素。但是,如果列表大小大于1,则新节点的next
元素将指向头部,而此新节点将是新head
。也就是说,新节点的next
元素将具有前一个head
元素的值。这就是为什么这种区别是必要的。