c 언어 데이터 구조 분석 2 의 링크 삽입 삭제

2452 단어 데이터 구조
#include <stdlib.h>

#include <stdio.h>

struct test{

	int value;

	struct test *next;

};

struct test* create(){ //  create   ,   struct test*              

	test *head,*tail,*p;

	head=tail=NULL;

	//head        ,p     ,tail        ,      

	int i;



	for(int j=0;j<4;j++)

	{

		scanf("%d",&i);

		//(    )malloc(sizeof(    ))       ,      free()   

		p=(struct test*)malloc(sizeof(struct test)); //         

		p->value=i;

		p->next=NULL;



		if(head==NULL)

		{

			head=tail=p;		//      

		}

		else{

			tail=tail->next;	//   set tail->next                  			

		}

		tail->next=p;			//         ;

	}



	return head;

};



struct test* insert(struct test* ar,int a,int b)	//      

{

	// a       ,b        ar       

	struct test *p,*q,*s;

	s=(struct test*)malloc(sizeof(struct test));

	s->value=b;



	if(ar==NULL)	//        

	{

		ar=s;

		s->next=NULL;

	}

	

	if(ar->value==a)//            ,      

	{

		s->next=ar;

		ar=s;

	}else{			//      

		p=ar;

		while(p->value!=a && p->next!=NULL)	//    a    ,while    

		{

			q=p;	//          p

			p=p->next;

		}

		if(p->value==a)	//      	

		{

			q->next=s;  //p         p       p         q

			s->next=p;

			

		}else		//        

		{

			p->next=s;

			s->next=NULL;

		}

	}



	

	return ar;

}

struct test* del(struct test* ar,int n)  //      

{

	struct test *q,*p;

	if(ar==NULL)

		printf("the table is null
"); else if(ar->value==n) { ar=ar->next; }else { p=ar; while(p->next!=NULL && p->value!=n) { q=p; p=p->next; } if(p->value!=n) printf("no the num
"); else { q->next=p->next; free(p); } } return ar; } void showDate(struct test* p)  // { while (p) { printf("%d
",p->value); p=p->next; } } int main(int argc, char* argv[]) { struct test *p,*head; int a,b,d; head=NULL; p=create(); head=p; showDate(p); printf("num
"); // scanf("%d",&a); printf("insert num
"); scanf("%d",&b); p=insert(head,a,b); head=p;// printf("new p
"); showDate(p); printf("del num
"); // scanf("%d",&d); p=del(head,d); showDate(p); return 0; }   

좋은 웹페이지 즐겨찾기