c语言的单链,C语言在单链列表的开头插入节点

例子

下面的代码将提示您输入数字,并继续将其添加到链接列表的开头。

/* 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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值