9.4 链表删除指定节点(静态创建链表)

①删除的是链表头

struct 	Test *delNode(struct Test *head,int data)
{
	struct Test *p =head;
	if(p->data == data){			//当删除的是链表头时
		head = head->next;
		//free(p);               //释放内存(链表头)
	return head;
	}
}

②删除的是非链表头

while(p->next != NULL){
		if(p->next->data== data){	
			p->next = p->next->next;
			return head;
		}
		p = p->next;
		
		
	}
	return head;

完整代码:

#include 
#include 
struct Test
{
	int data;
	struct Test *next;
};

void printLink(struct Test *head)
{
	while(1){
		if(head != NULL){
		printf("%d ",head->data);
		head = head->next;
		}else{
			printf("\n");
			break; 
		}
	}
}



struct 	Test *delNode(struct Test *head,int data)
{
	struct Test *p =head;
	if(p->data == data){			//当删除的是链表头时
		head = head->next;
	return head;
	}
	while(p->next != NULL){
		if(p->next->data== data){	
			p->next = p->next->next;
			return head;
		}
		p = p->next;
		
		
	}
	return head;
}
int main(){
	struct Test t1 = {1,NULL};
	struct Test t2 = {2,NULL};
	struct Test t3 = {3,NULL};
	struct Test t4 = {4,NULL};
	
	t1.next = &t2;
	t2.next = &t3;
	t3.next = &t4;
	
	struct Test *head = &t1;
	printLink(&t1);
	head = delNode(head,4);
	printLink(head);
	
	
	
	return 0;
}

你可能感兴趣的:(C语言,c语言,linux)