链表之删除

#include<stdio.h>
#include<stdlib.h> 


struct test
{
    
    
	int data;
	struct test *next;
};

void printLink(struct test* head)
{
    
    
	struct test *point=head;
	while(point!=NULL)
	{
    
    
		printf("%d  ",point->data);
		point=point->next;
	}
	putchar('\n');
 } 



struct test *deleteNode(struct test* head,int data)
{
    
    
	struct test *p=head;
	if(p->data==data)//若第一个为要删除的
	{
    
    
		head=p->next;
		return head;
	}
	while(p->next!=NULL)//若后面元素需删除的
	{
    
    
		if(p->next->data==data)
		{
    
    
			p->next=p->next->next;
			return head;
		}
		p=p->next;
		
	}
}
int main()
{
    
    

	struct test t1={
    
    1,NULL};
	struct test t2={
    
    2,NULL};
	struct test t3={
    
    3,NULL};
	struct test t4={
    
    4,NULL};
	struct test t5={
    
    5,NULL};
	
	
	t1.next=&t2;
	t2.next=&t3;
	t3.next=&t4;
	t4.next=&t5;
	
	int c,d;
	struct test *head=NULL;
	printf("Please tell me which num  you want to delete:\n");
	scanf("%d",&c);
	if(c>5||c<1)
	{
    
    
		printf("NO THIS WORD!\n");
		exit(-1);
	}

	
	head=&t1;
	printLink(head);
	head=deleteNode(head,c);
	printLink(head);
			

	return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43482790/article/details/114898680