单链表之插入函数

int insert_node(node** root_point, int insert_value) //插入函数,第一个参数为指向头结点指针的指针,第二个参数为插入的值。
                                            //因为你想要插入的值可能要放在第一个节点前面。
{
	node* current;   //指向现在所在的节点
	node* previous;  //指向前一个节点
	node* new_node;  //新的节点
	current = *root_point;
	previous = NULL;
	/*
	寻找插入位置,按序访问链表,知道找到一个其值大于或等于新值的节点
	*/
	while (current!=NULL&&current->data<insert_value)
	{
		previous = current;
		current = current->next;
	}
	/*
	为新的节点(new_node)分配内存,并把值储存在新的节点内
	如果分配内存失败返回0。
	*/
	new_node = (node*)malloc(sizeof(Node));
	if (new_node == NULL)
		return false;
	new_node->data = insert_value;
	//把新节点插入链表
	new_node->next = current;
	if (previous==NULL)
	{
		*root_point = new_node;
	}
	else
	{
		previous->next = new_node;
	}
	return 1;
}

下一章为优化插入函数

带头结点的单链表插入函数通常有在指定位置插入、头插法插入和尾插法插入等方式,以下是详细的实现及使用说明。 #### 代码实现 ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构 typedef struct Node { int data; struct Node* next; } Node, *List; // 链表初始化 bool Init(List *L) { *L = (Node *)malloc(sizeof(Node)); // 创建头结点 if (*L == NULL) { return false; } (*L)->next = NULL; return true; } // 在指定位置插入元素 bool Insert(List L, int pos, int e) { if (pos < 1) { return false; } Node *p = L; int j = 0; while (p != NULL && j < pos - 1) { p = p->next; j++; } if (p == NULL) { return false; } Node *s = (Node *)malloc(sizeof(Node)); if (s == NULL) { return false; } s->data = e; s->next = p->next; p->next = s; return true; } // 头插法插入元素 void HeadInsert(List L, int e) { Node *s = (Node *)malloc(sizeof(Node)); s->data = e; s->next = L->next; L->next = s; } // 尾插法插入元素 void TailInsert(List L, int e) { Node *p = L; while (p->next != NULL) { p = p->next; } Node *s = (Node *)malloc(sizeof(Node)); s->data = e; s->next = NULL; p->next = s; } // 打印链表 void PrintList(List L) { Node *p = L->next; while (p != NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); } int main() { List L; Init(&L); // 头插法插入元素 HeadInsert(L, 2); HeadInsert(L, 1); // 尾插法插入元素 TailInsert(L, 3); // 在指定位置插入元素 Insert(L, 2, 4); // 打印链表 PrintList(L); return 0; } ``` #### 代码解释 1. **链表初始化**:`Init` 函数用于创建头结点,并将其 `next` 指针置为 `NULL`,表示链表为空。 2. **在指定位置插入元素**:`Insert` 函数会先判断插入位置是否合法,然后找到插入位置的前一个节点,再创建新节点插入到该位置。 3. **头插法插入元素**:`HeadInsert` 函数将新节点插入到头结点之后,成为新的首节点。 4. **尾插法插入元素**:`TailInsert` 函数会遍历链表找到尾节点,然后将新节点插入到尾节点之后。 5. **打印链表**:`PrintList` 函数用于遍历链表并打印每个节点的数据。 #### 使用方法 在 `main` 函数中,首先调用 `Init` 函数初始化链表,然后可以根据需要调用 `HeadInsert`、`TailInsert` 或 `Insert` 函数插入元素,最后可以调用 `PrintList` 函数打印链表中的元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值