查找链表指定位置的节点 -- C语言

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

代码实现

st_dataNode* findListPos(st_dataNode* head, int pos){
	if(NULL == head || pos < 0){
		return NULL;
	}

	if(0 == pos) {
		return head;
	}

	st_dataNode * p = NULL;
	st_dataNode * q = NULL;
	int len = getListLen(head);

	if(pos > len) {
		printf("超过链表长度了!\n");
		return NULL;
	}

	p = head;
	while(p != NULL){
		if(pos-- == 0){
			q = p;
			break;
		}
		p = p->next;
	}

	return q;
}


void testFindListPos(void){
	st_dataNode * rst = NULL;
	
	rst = findListPos(ghead, -1);
	if(NULL != rst){
		printf("find pos -1 node: %p, data = %d\n", rst, rst->data);
	} else {
		printf("Can not found pos -1 node \n");
	}	

	rst = findListPos(ghead, 0);
	if(NULL != rst){
		printf("find pos 0 node: %p, data = %d\n", rst, rst->data);
	} else {
		printf("Can not found pos 0 node \n");
	}		

	rst = findListPos(ghead, 5);
	if(NULL != rst){
		printf("find pos 5 node: %p, data = %d\n", rst, rst->data);
	} else {
		printf("Can not found pos 5 node \n");
	}	

	rst = findListPos(ghead, 12);
	if(NULL != rst){
		printf("find pos 12 node: %p, data = %d\n", rst, rst->data);
	} else {
		printf("Can not found pos 12 node \n");
	}	

	return;
	
}

代码调试

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

调试输出

========= Dump List 0x8ca010 ===========
         22  32  19  53  0  47  29  116  4  6
===================================
List length = 10
node: 0x8ca130, data = 6
Can not found num 119
Can not found pos -1 node
find pos 0 node: 0x8ca010, data = 22
find pos 5 node: 0x8ca0b0, data = 47
超过链表长度了!
Can not found pos 12 node

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值