双向链表节点的删除 — C语言

  • Post author:
  • Post category:其他


代码实现

st_doubNode * removeDoubListNode(st_doubNode** phead, int pos){
	if(NULL == phead || pos < 0){
		printf("%s: param error\n",__func__);
		return NULL;
	}

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

	if(0 == pos) { /*首节点*/
		/*摘掉*/
		nw = head;
		p = head->next;
		p->prev = NULL;

		/*清除*/
		nw->next = NULL;
		nw->prev = NULL;

		/*更新头*/
		head = p;
		
	} else { /* 其他节点 */
		nw = findDoubListPos(head, pos);
		p = nw->next;
		q = nw->prev;

		p->prev = q;
		q->next = p;

		nw->next = NULL;		
		nw->prev = NULL;
	}

	*phead = head;

	return nw;
}


void testremoveDoubListNode(void){
	st_doubNode * nw = NULL;

	printf("\n************  testremoveDoubListNode ************ \n");
	
	nw = removeDoubListNode(&gDoubHead, 11);
	if(NULL != nw)
		printf("Removed node %p: data %d\n", nw, nw->data);
	dumpDoubList(gDoubHead);
	
	nw = removeDoubListNode(&gDoubHead, 5);
	if(NULL != nw)
		printf("Removed node %p: data %d\n", nw, nw->data);
	dumpDoubList(gDoubHead);
	
	nw = removeDoubListNode(&gDoubHead, 0);
	if(NULL != nw)
		printf("Removed node %p: data %d\n", nw, nw->data);	
	dumpDoubList(gDoubHead);
	dumpDoubListReverse(gDoubHead);

	return;
}

代码编译

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

调试输出

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


************  testremoveDoubListNode ************
Removed node 0x9ba190: data 66
========= Dump Double List 0x9ba150 ===========
         70  22  32  19  53  31  0  47  29  116  4  6
===================================
Removed node 0x9ba170: data 31
========= Dump Double List 0x9ba150 ===========
         70  22  32  19  53  0  47  29  116  4  6
===================================
Removed node 0x9ba150: data 70
========= Dump Double List 0x9ba010 ===========
         22  32  19  53  0  47  29  116  4  6
===================================



版权声明:本文为leoufung原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。