在单链表的开头插入节点
下面的代码将提示输入数字并继续将它们添加到链接列表的开头。
/* This program will demonstrate inserting a node at the beginning of a linked list */
#include <stdio.h>
#include <stdlib.h>
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 < listSize; 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;
完成的