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

代码实现

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
发布了191 篇原创文章 · 获赞 43 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/leoufung/article/details/104334835
今日推荐