单链表的插入

本文介绍了两种在带头结点的单链表中插入元素的方法:一种是在指定位置i前插入,另一种是在找到第一个值为e的节点前插入。提供了详细的C语言实现代码,包括函数参数说明及作者信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct Node { int Data; struct Node* next; }; /** * @brief 该函数实现了在带头结点单链表中第i个结点之前插入元素 * @param[in] head 待插入结点链表 * @param[in] i 待插入结点位置 * @param[in] e 待插入结点值 * @author wlq_729@163.com * http://blog.youkuaiyun.com/rabbit729 * @version 1.0 * @date 2009-03-09 */ int ListInsert(Node* head, const int i, const int e) { assert(head); if (head->next == NULL) { return -1; } // 寻找待插入结点的前驱结点,并用prior指向待删除结点的前驱结点 int j = 0; Node* prior = head; while ((prior->next != NULL) && (j < i-1)) { prior = prior->next; j++; } // 插入结点 Node* q = new Node; assert(q); q->Data = e; q->next = prior->next; prior->next = q; return 0; } /** * @brief 该函数实现了在带头结点单链表中与给定值相等的第一个结点前插入结点 * @param[in] head 待插入结点链表 * @param[in] e 待插入结点的位置 * @param[in] data 待插入结点值 * @author wlq_729@163.com * http://blog.youkuaiyun.com/rabbit729 * @version 1.0 * @date 2009-03-09 */ int ListInsert1(Node* head, const int e, int data) { assert(head); if (head->next == NULL) { return -1; } Node* q = head->next; Node* prior = head; while ((q != NULL) && (q->Data != e)) { prior = q; q = q->next; } // 插入结点 if((q != NULL) && (q->Data == e) ) { Node* t = new Node; assert(t); t->Data = data; t->next = prior->next; prior->next = t; return 0; } else { cout<<"Could not find data!"<<endl; return -1; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值