单链表的基本操作之增 删 查 改(C语言实现)

单链表的基本操作:增 删 查 改

#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
struct node
{
	int data;
	struct node *next;
};

int main()
{
	struct node *head,*p,*q,*t;
	int i,n,a,b,c;
	printf("please input n:");
	scanf("%d",&n);
	head=NULL;
	for(i=1;i<=n;i++){
		scanf("%d",&a);
		p=(struct node *)malloc(sizeof(struct node));
     	p->data=a;
		p->next=NULL;
		if(head==NULL)
			head=p;
		else
			q->next=p;
		q=p;
	}
    printf("Please input your choice:1. insert 2. del 3.update 4.find\n");
	int m;
	scanf("%d",&m);
	printf("please input you change number:\n");
    scanf("%d",&a);
	t=head;
	switch(m)
	{
		case 1:
		{
	
			while(t!=NULL)
			{
				if(t->next->data==a)
				{
					printf("please input your insert number:\n");
					scanf("%d",&c);
					p=(struct node *)malloc(sizeof(struct node));
					p->next=t->next;
					p->data=c;
					t->next=p;
					break;
				}
				t=t->next;
			}
			if(t==NULL) return ERROR;
				;
			break;
	    }
		case 2:
		{
			while(t!=NULL)
			{
				if(t->next->data==a)
				{
					t->next=t->next->next;
					break;
				}
				t=t->next;
			}
			if(t==NULL) return ERROR;
			break;
        }
		case 4:
		{
			while(t!=NULL)
				{
					if(t->next->data==a)
					{
                        printf("%d",t->next->data);
				        exit(0);
					}
					
					t=t->next;
				}
			if(t==NULL) return ERROR;
			break;
		}
        case 3:
		{
			while(t!=NULL)
			{
				if(t->next->data==a)
				{
					printf("update=");
					scanf("%d",&b);
					t->next->data=b;
					break;
				}
				t=t->next;
			}
			if(t==NULL) return ERROR;
			break;
		}
		default:
		{
			return 0;
		}	
    }
	t=head;
	while(t!=NULL)
	{
		printf("%d",t->data);
		t=t->next;
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42735631/article/details/82668490