链表之指定位置插入

指定位置插入:
做这种查找类的插入,先不要着急创建节点,要考虑没找到的情况,没找到就不需要创建节点

#include<stdio.h>
struct Node
{
   
	int data;
	struct Node* next;
}
//创建头节点
struct Node* createHead()
{
   
	struct Node* headNode=(struct Node*)malloc(sizeof(struct Node));
	if(headNode==NULL)
	{
   
		return 0;
	}
	headNode->next=NULL;
	return headNo
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
双向链表指定位置插入操作可以通过以下步骤实现: 1. 首先,需要对插入位置进行合法性判断,确保插入位置链表范围内。 2. 然后,找到插入位置的前一个节点,可以通过遍历链表来找到该节点。 3. 创建一个新的节点,并将要插入的数据存储在该节点中。 4. 将新节点的next指针指向插入位置的节点,将新节点的prev指针指向插入位置的前一个节点。 5. 将插入位置的前一个节点的next指针指向新节点,将插入位置的节点的prev指针指向新节点。 6. 插入完成后,更新链表的长度等相关信息。 以下是一个示例代码,用于在双向链表指定位置插入元素: ```java private Node searchIndex(int index) { if (index < 0 || index > getLength()) { throw new UnsupportedOperationException("下标不合法"); } int count = 0; Node cur = this.head; while (count != index) { cur = cur.next; count++; } return cur; } public boolean addIndex(int index, int data) { Node cur = searchIndex(index); Node node = new Node(data); if (index == 0) { addFirst(data); return true; } if (index == getLength()) { addLast(data); return true; } node.next = cur; cur.prev.next = node; node.prev = cur.prev; cur.prev = node; return true; } ``` 在上述代码中,searchIndex方法用于找到插入位置的节点,addIndex方法用于在指定位置插入新节点。注意,如果插入位置链表的头节点或尾节点,可以直接调用addFirst或addLast方法来完成插入操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值