C语言 插入到一个有序的单链表

代码如下:
/*
** 插入到一个有序的单链表, 函数的参数是一个指向链表第一个节点的指针,
** 以及一个需要插入的新值 
*/
 
#include <stdio.h>
#include <stdlib.h>
#include "sll_node.h"

#define FALSE   0
#define TRUE    1

int
sll_insert( register Node **linkp, int new_value )
{
	register Node *current;
	register Node *new;
	
	/*
	** 寻找正确的插入位置,方法是按序访问链表,直到到达一个其值大于或等于新值的节点
	*/
	
	while( ( current = *linkp ) != NULL && current->value < new_value )
		linkp = ¤t -> link;
		
	/*
	** 为新节点分配内存, 并把新值存储到新节点中,如果内存分配失败,函数返回FALSE
	*/
	
	new = ( Node *)malloc( sizeof(int));
	if (new == NULL )
		return FALSE;
	new->value = new_value;
	
	/*
	** 在链表中插入新节点,并返回TURE
	*/
	
	new->link = current;
	 *linkp = new; 
	 return TURE;
} 

可以按照以下步骤来实现两个有序单链表的合并到新的链表: 1. 定义链表节点结构体,包含数据和指向下一个节点的指针。 ```c struct ListNode { int val; struct ListNode *next; }; ``` 2. 实现一个函数 `mergeTwoLists`,接收两个链表的头指针,返回合并后的链表头指针。 ```c struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { // 如果两个链表中有一个为空,则直接返回另一个链表 if (l1 == NULL) return l2; if (l2 == NULL) return l1; // 定义一个新链表的头指针和尾指针 struct ListNode dummy; struct ListNode *tail = &dummy; // 遍历两个链表,将较小值的节点插入到新链表的尾部 while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } // 将剩余的节点插入到新链表尾部 if (l1 != NULL) tail->next = l1; if (l2 != NULL) tail->next = l2; // 返回新链表的头指针 return dummy.next; } ``` 这个函数会遍历两个链表,将较小值的节点插入到新链表的尾部,最后返回新链表的头指针。 可以使用以下代码测试这个函数的正确性: ```c int main() { struct ListNode l1_3 = {4, NULL}; struct ListNode l1_2 = {2, &l1_3}; struct ListNode l1_1 = {1, &l1_2}; struct ListNode l2_3 = {7, NULL}; struct ListNode l2_2 = {3, &l2_3}; struct ListNode l2_1 = {1, &l2_2}; struct ListNode *merged = mergeTwoLists(&l1_1, &l2_1); while (merged != NULL) { printf("%d ", merged->val); merged = merged->next; } printf("\n"); return 0; } ``` 输出应该为:`1 1 2 3 4 7`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值