동적 체인 연습 (단선 체인 연습)

3377 단어
#include "stdafx.h"




#include <iostream>
using namespace std;
struct Data    // 
{
int data;
Data *next;
};
int n;
int main (  )   // 
{Data * creat(void )  ;     //     
Data * del(Data * ,int );// 
Data *insert (Data * head,Data * da);// 
void print (Data *head);// 
int look(Data *head, int a);   //  
Data  * head,*da;
int b,m;
da=new Data ;
head=creat ();   // 
print (head);    // 
cout <<"please input the data you insert: "<<endl;
cin >>da->data;
head=insert (head,da);// 
print (head);     // 
cout <<"please input the data you delete :  "<<endl;
cin >>b;
head=del(head,b);  // 
print (head);     // 
cout <<"please input the data you look : "<<endl;
cin >>m;
look(head,m);  // 
return 0;
}

Data * creat(void )       //                               
{Data *p1,*p2,*head;

n=0;
p1=p2=new Data;
cout <<"Please input data: "<<endl;
cin>>p1->data;
head=NULL;
while (p1->data!=0)
{n++;
if (n==1)
	head=p1;
else p2->next=p1;

p2=p1;
p1=new Data;
cout <<"Please input data:"<<endl;
cin>>p1->data;}
p2->next=NULL;
return (head);


}
void print (Data *head)// 
{Data *p1;
p1=head;
if (head==NULL)
cout <<"list null"<<endl;
else
	{cout <<endl<<"The datas are : "<<endl;
	do{cout <<p1->data<<endl;
       p1=p1->next;}while (p1!=NULL);
    }
}
int look(Data *head, int a)    // 
{Data *p1;
int m=0;
p1=head;
if (head==NULL)
{cout <<endl<<"List null"<<endl;return 0;}
while (p1->next!=0)
{if (p1->data==a)
   m=m+1;
p1=p1->next;}
cout <<endl<<"There is "<<m<<" data"<< a<<"!!"<<endl;
return 0;

}
Data *insert (Data * head,Data * da)// 
{Data *p1,*p2;
 p1=head;
  if (head==NULL)
	  {head=da;
      da->next=NULL;
       }
  else 
     {while (da->data>p1->data)
       {p2=p1;
       p1=p1->next;
            }
        if (da->data<=p1->data )
			{if (head==p1)
				head=da;
			else p2->next=da;
		    da->next =p1;
     }
		else {p1->next=da;da->next =NULL;}
		n=n+1;}
		return head;
}
Data *del (Data * head,int da)  // 
{Data *p1,*p2;
p1=head;
if (head ==NULL)
	cout <<"List null"<<endl;
while (da!=p1->data&&p1->next!=NULL)
{p2=p1;
p1=p1->next;
}
if(da==p1->data)
{if (p1==head)
  head=p1->next;
else p2->next=p1->next;
cout <<"delete "<<da<<"!"<<endl;
}
else cout <<"cannot find"<<da<<"!"<<endl;
return head;
}

좋은 웹페이지 즐겨찾기