例子
下面的代码将提示您输入数字,并继续将其添加到链接列表的开头。
/* This program will demonstrate inserting a node at the beginning of a linked list */
#include
#include
struct Node {
int data;
struct Node* next;
};
void insert_node (struct Node **head, int nodeValue);
void print_list (struct Node *head);
int main(int argc, char *argv[]) {
struct Node* headNode;
headNode = NULL; /* Initialize our first node pointer to be NULL. */
size_t listSize, i;
do {
printf("How many numbers would you like to input?\n");
} while(1 != scanf("%zu", &listSize));
for (i = 0; i
int numToAdd;
do {
printf("Enter a number:\n");
} while (1 != scanf("%d", &numToAdd));
insert_node (&headNode, numToAdd);
printf("Current list after your inserted node: \n");
print_list(headNode);
}
return 0;
}
void print_list (struct Node *head) {
struct node* currentNode = head;
/* Iterate through each link. */
while (currentNode != NULL) {
printf("Value: %d\n", currentNode->data);
currentNode = currentNode -> next;
}
}
void insert_node (struct Node **head, int nodeValue) {
struct Node *currentNode = malloc(sizeof *currentNode);
currentNode->data = nodeValue;
currentNode->next = (*head);
*head = currentNode;
}
插入节点的说明
为了了解我们在一开始如何添加节点,让我们看一下可能的情况:该列表为空,因此我们需要添加一个新节点。在这种情况下,我们的内存如下所示,其中HEAD是指向第一个节点的指针:
| HEAD | --> NULL
该生产线currentNode->next = *headNode;将分配的值currentNode->next是NULL因为headNode原本在一个值开始NULL。
现在,我们要设置头节点指针指向当前节点。
----- -------------
|HEAD | --> |CURRENTNODE| --> NULL /* The head node points to the current node */
----- -------------
这是用完成的 *headNode = currentNode;该列表已被填充;我们需要在开头添加一个新节点。为了简单起见,让我们从1节点开始:
----- -----------
HEAD --> FIRST NODE --> NULL
----- -----------
使用currentNode->next = *headNode,数据结构如下所示:
--------- ----- ---------------------
currentNode --> HEAD --> POINTER TO FIRST NODE --> NULL
--------- ----- ---------------------
这显然需要更改,因为*headNode应该指向currentNode。
---- ----------- ---------------
HEAD -> currentNode --> NODE -> NULL
---- ----------- ---------------
这是用完成的 *headNode = currentNode;