将Node插入到第一位的C编程中

这是我正在编写的程序的一个function,以便更熟悉节点。 我不确定它是否正确,但实质上是检查Node是否为Null,如果是,那么它将信息添加到代码字段并将指针设置为NULL。

否则,它会创建一个新节点并将信息插入代码字段,然后指向现有的第一个节点。 我不确定如何更改指向原始第一个节点的标头指向新节点。 代码是

typedef struct node { LibraryCode location; struct node *next; } Node; void insertFirstNode(LibraryCode code, Node **listPtr) { Node *n=*listPtr; Node *first; if(n==NULL){ n=malloc(sizeof(Node)); n->location=code; n->next=NULL; } else { Node *first; first->location=code; first->next=n; } } 

您需要无条件地创建新节点(并将位置设置为新值)。

如果已有列表,您可能希望在列表的前面插入此节点,如果没有列表,那么这将成为第一个节点? 注意重命名的function; 它反映了一个节点将永远插入的事实。

插在前面

 void insertNode(LibraryCode code, Node **listPtr) { Node *new_node = malloc(sizeof(*new_node)); if (new_node == 0) err_exit("Out of memory"); new_node->location = code; new_node->next = *listPtr; *listPtr = new_node; } 

插入结束

如果您想在列表的末尾插入(如果已有列表),则:

 void insertNode(LibraryCode code, Node **listPtr) { Node *new_node = malloc(sizeof(*new_node)); if (new_node == 0) err_exit("Out of memory"); new_node->location = code; new_node->next = NULL; if (*listPtr == NULL) *listPtr = new_node; else { Node *node = *listPtr; while (node->next != NULL) node = node->next; node->next = new_node; } } 

如果您希望在已经分配列表的情况下挽救错误,那么您需要重新考虑您的API设计。

** listPtr是持有或保持列表的头节点的地址。 如果* listPtr == null,那么列表为空我根据提供的内容判断为约定。 无论如何,我们需要为所提供的LibraryCode构建一个新的Node。 所以有点缩短(一些error handling没有拼写出来)..

 void insertFirstNode(LibraryCode code, Node **listPtr){ node = malloc( sizeof(Node) ); node->location = code; node->next = *listPtr; *listPtr = node; } 

基本上,你有两个选择。 如果现有的listPtr为null,那么你有一个空列表,只需要创建它的第一个条目。 如果listPtr不为null,则列表已经存在,您只需要将新节点填充到列表的开头。

所以在伪代码中:

 if (listptr == null) { ... empty chain, create one n = malloc(...); n->location = code; n->next = null; } else { ... got an existing chain n = malloc(...); n->location = code; n->next = listptr; // make previous top of chain be a child of new node} } return n;