用C语言建立一个链表实现一个通讯录,
发布网友
发布时间:2022-05-13 15:38
我来回答
共1个回答
热心网友
时间:2023-10-14 18:29
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef unsigned long ulong;
typedef struct _list {
char name[16];
char addr[64];
ulong phone;
ulong qq;
struct _list* next;
} *node, list;
/* insert a node */
node Insert( node* head, node pos, list* l )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
strcpy( tmp->name, l->name );
strcpy( tmp->addr, l->addr );
tmp->phone = l->phone;
tmp->qq = l->qq;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
/* create a list */
node Create( void )
{
node head, t;
list input;
head = t = NULL;
printf( "请按 [姓名] [地址] [家庭电话] [qq] 的顺序输入\n" );
printf( "每行一组数据,输入空行结束:\n" );
while ( 1 ) {
if ( getchar() == '\n' ) break;
scanf( "%s%s%lu%lu", input.name, input.addr, &input.phone, &input.qq );
while ( getchar() != '\n' );
t = Insert( &head, t, &input );
}
return head;
}
/* view list */
void Print( node head )
{
while ( head ) {
printf( "%s\t%s\t%lu\t%lu\n", head->name, head->addr, head->phone, head->qq );
head = head->next;
}
putchar( '\n' );
}
/* merge sort */
node msort( node* head, int n )
{
int i, m;
node l, r, p, *x, *y;
if ( n < 2 ) return *head;
m = n/2;
p = l = r = *head;
for ( i = m; i > 0; --i )
p = r, r = r->next;
p->next = NULL;
l = msort( &l, m );
r = msort( &r, n - m );
x = &p;
while ( l && r ) {
*x = l->qq < r->qq ? (y = &l, l) : (y = &r, r);
*y = (*y)->next; x = &(*x)->next;
}
l = l ? l : r ? r : NULL;
*x = l; *head = p;
return p;
}
/* sort wrapper */
void Sort( node* head )
{
int i;
node tmp = *head;
for ( i = 0; tmp; ++i, tmp = tmp->next );
msort( head, i );
}
int main( void )
{
node head = Create();
printf( "\n链表内容:\n" );
Print( head );
Sort( &head );
printf( "\n排序之后:\n" );
Print( head );
getch();
return 0;
}