将节点插入第一名C编程



这是我编写的程序的函数,以使节点更熟悉。我不确定它是否正确,但本质上是检查节点是否为null如果是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;
    }
}

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

如果已经有一个列表,您可能想将此节点插入列表的正面,如果没有列表,那么这将成为第一个节点?注意重命名的功能;它反映了一个节点将始终插入的事实。

在前插入

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

end

插入

如果您想在列表的末端插入列表,则:

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,则列表为空,我假定从提供的内容来判断。无论如何,我们需要为提供的库代码构建一个新节点。因此有点缩短(某些错误处理未阐明)..

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

基本上,您有两个选择。如果现有的listPtr为null,则您有一个空列表,只需要创建其第一个条目即可。如果ListPtr不是null,则已经存在一个列表,您只需要将一个新节点塞入列表的开头。

so so in pseudo-ish代码:

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;

最新更新