Try to write a program that reads contact data from the command line, sorts the data
alphabetically and again displays the ordered data on the screen. A possible session of the
program could be :
student@localhost:~$ ./sort_persons
Please input persons name : Jan
Please input persons phone : 0112
Please input persons name : Piet
Please input persons phone : 0194
Please input persons name : Joris
Please input persons phone : 0135
Please input persons name : Korneel
Please input persons phone : 0148
Please input persons name : STOP
Sorting Data ...
Jan – 0112
Joris – 0135
Korneel – 0148
Piet – 0194
student@localhost:~$
To do so you should work in an object oriented way. Sorting person objects rather then
strings. Your program thus contains a minimum of 3 files, e.g. main.c, person.h and
person.c
放假在家也沒什麼事兒幹,試著寫了個,很久沒弄鏈表之類的東西了,都快忘了,自己感覺實現的是不怎麼好~~ 大家見了多多指點
/**********************************person.h******************************/
#define SIZE sizeof (struct dat)
struct dat
{
char name[20];
char phone[20];
struct dat * next;
};
/*********************************person.c******************************/
#include<string.h>
#include<stdlib.h>
#include "person.h"
struct dat * head;
int n;
/*建立鏈表*/
void creat()
{
struct dat *p1,*p2;
n=1;
p1=p2=( struct dat * ) malloc(SIZE);
printf ("Please input persons name:");
scanf ("%s",&p1->name);
printf ("Please input persons phone:");
scanf ("%s",&p1->phone);
head=p1;
while (strcmp(p1->name,"STOP"))
{
n=n+1;
p2->next=p1;
p2=p1;
p1=(struct dat *)malloc (SIZE);
printf ("Please input persons name:");
scanf ("%s",&p1->name);
if (!(strcmp(p1->name,"STOP"))) break;
printf ("Please input persons phone:");
scanf ("%s",&p1->phone);
}
p2->next=p1;
}
/*在鏈表內部排序,這裡用的是"冒泡" OOoo*/
void storing(struct dat * p)
{
int j,i;
struct dat * before,* after;
char tmp[20];
for (j=1;j<=(n-2);j++)
{
before=after=p;
for (i=1;i<=(n-1)-j;i++)
{
before=after;
after=after->next;
if ((strcmp(before->name,after->name)>0))
{
strcpy (tmp,before->name);
strcpy (before->name,after->name);
strcpy (after->name,tmp);
}
if ((strcmp(before->phone,after->phone)>0))
{
strcpy (tmp,before->phone);
strcpy (before->phone,after->phone);
strcpy (after->phone,tmp);
}
}
}
}
/*輸出鏈表*/
void print (struct dat *h)
{
struct dat * p;
printf ("\nSorting Data ... ");
printf ("\n");
p=h;
do
{
printf ("%s - %s\n",p->name,p->phone);
p=p->next;
}while (strcmp(p->name,"STOP"));
}
/************************************main.c********************************/
#include<stdio.h>
#include"person.c"
int main()
{
creat(head);
storing(head);
print(head);
}