双向链表按位置查找 -- C语言

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

代码实现

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

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

	st_doubNode * p = NULL;
	st_doubNode * q = NULL;
	int len = getDoubListLen(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 testFindDoubListPos(void){
	st_doubNode * rst = NULL;
	
	rst = findDoubListPos(gDoubHead, -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 = findDoubListPos(gDoubHead, 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 = findDoubListPos(gDoubHead, 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 = findDoubListPos(gDoubHead, 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 doublist.c listMain.c -DDEBUG -o a.exe

调试输出

************  testCreateDoubList ************
========= Dump Double List 0x13f4010 ===========
         22  32  19  53  0  47  29  116  4  6
===================================
************  testCreateDoubList ************
len  = 10


************  testFindDoubListPos ************
Can not found pos -1 node
find pos 0 node: 0x13f4010, data = 22
find pos 5 node: 0x13f40b0, data = 47
超过链表长度了!
Can not found pos 12 node

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值