在链表的指定位置插入节点 -- C语言

83 篇文章 2 订阅
30 篇文章 0 订阅

这里有个小技巧,容易错误。传入的是个双重指针 st_dataNode** phead,因为插入在首节点的位置时候,链表头的位置会发生改变,指向新的节点,所以需要传入双重指针,以便接收修改的新的链表头的位置

代码实现

/*
 * 传入head是二重指针,是因为插入头结点的时候,会改变head的指向到新的节点
 */
st_dataNode * insertListNode(st_dataNode** phead, int pos, int data){
	if(NULL == phead || pos < 0){
		printf("%s: param error\n",__func__);
		return NULL;
	}

	st_dataNode * head = *phead;
	st_dataNode * p = NULL;
	st_dataNode * q = NULL;
	st_dataNode * nw = NULL;

	nw = (st_dataNode *) malloc(sizeof(st_dataNode));
	if(NULL == nw){
		printf("%s: memory alloc failed\n", __func__);
		return NULL;
	}
	nw->data = data;

	if(0 == pos){ // 首节点
		p = head;
		nw->next = p;
		*phead = nw; /*插入后更新首节点的值*/
	} else { // 中间节点
		/* 注意,要找前面一个节点,单链表才能前后都链接上*/
		p = findListPos(head, pos - 1);
		q = p->next;
		p->next = nw;
		nw->next = q;	
	}

	return nw;
}


void testInsertNode(void){
	st_dataNode * nw = NULL;
	nw = insertListNode(&ghead, 0, 70);	
	dumpList(ghead);
	
	insertListNode(&ghead, 5, 31);
	dumpList(ghead);
	
	insertListNode(&ghead, 12, 66);
	dumpList(ghead);

	return;
}

调试编译

gcc listMain.c list.c -o a.exe -DDEBUG

调试输出

========= Dump List 0xef3010 ===========
         22  32  19  53  0  47  29  116  4  6
===================================
List length = 10
node: 0xef3130, data = 6
Can not found num 119
Can not found pos -1 node
find pos 0 node: 0xef3010, data = 22
find pos 5 node: 0xef30b0, data = 47
超过链表长度了!
Can not found pos 12 node
========= Dump List 0xef3150 ===========
         70  22  32  19  53  0  47  29  116  4  6
===================================
========= Dump List 0xef3150 ===========
         70  22  32  19  53  31  0  47  29  116  4  6
===================================
========= Dump List 0xef3150 ===========
         70  22  32  19  53  31  0  47  29  116  4  6  66
===================================

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值