![]() |
#2
freeskying2007-10-30 19:12
以前学数据结构时写的:
#include<alloc.h> #define NULL 0 #define ture 1 #define false 0 #define LEN sizeof(struct linklist) struct linklist/*结构体*/ { float data; struct linklist *next; };/*定义结构体结点*/ int n; struct linklist *print(struct linklist *head)/*打印单链表*/ { struct linklist *temp; for(temp=head;temp!=NULL;temp=temp->next) printf("%-8.2f",temp->data); } struct linklist *creat()/*建立单链表*/ { struct linklist *head,*tail,*p; n=0; p=(struct linklist *)malloc(LEN); scanf("%f",&p->data); while(p->data!=0) { if(n==0) { head=p; tail=head; } else tail->next=p; tail=p; p=(struct linklist *)malloc(LEN); scanf("%f",&p->data); n++; } tail->next=NULL; print(head); return(head); } struct linklist * delete(struct linklist *head,int i)/*删除单链表*/ { struct linklist *p1,*p2; int j=1; if(head==NULL || i<0 || i>n) { printf("\nERROR\n");goto end; } p1=head; while(j!=i) { p2=p1; p1=p1->next;j++; } if(p1==head) head=p1->next; else p2->next=p1->next; printf("\ndelete:%-8.2f\n",p1->data); n--;print(head);end:; return(head); } struct linklist *insert(struct linklist *head,float elem,int i)/*插入单链表*/ { struct linklist *p0,*p1,*p2; int j; if(i>=1 && i<=n) { if(i==1) { p1=(struct linklist *)malloc(LEN); p1->data=elem; p1->next=head; head=p1; } else { j=1; p0=head; while(j!=i) { p1=p0; p0=p0->next; j++; } p2=(struct linklist*)malloc(LEN); p2->data=elem; p2->next=p0; p1->next=p2; } n++; print(head); return(head); } else printf("\nERROR\n"); } int locate(struct linklist *head,float elem)/*查找单链表*/ { struct linklist *temp; int i=1; temp=head; while(i<=n) { if(temp->data==elem) return(1); else temp=temp->next; i++; } return(0); } main() { struct linklist *head; int i,s; float elem; printf("\ninput elem:\n"); head=creat(); printf("\nplease select:1.insert 2.delete 3.locate 4.exit:\n"); scanf("%d",&s); while(s!=4) { switch(s) { case 1 :{ printf("\nelem&locate\n"); scanf("%f,%d",&elem,&i); head=insert(head,elem,i); }break; case 2 :{ printf("\nlocate\n"); scanf("%d",&i); head=delete(head,i); }break; case 3 :{ printf("\nelem\n"); scanf("%f",&elem); locate(head,elem)?printf("\nFind the elem\n"):printf("\nCan not find the elem\n"); }break; case 4 :exit(0); } printf("\nplease select:1.insert 2.delete 3.locate 4.exit:\n"); scanf("%d",&s); } } |
如题所示,先谢谢了!!!