本帖最后由 代码农民 于 2016-12-29 21:46 编辑 //dblist.h
#ifndef _DB_LIST
#define _DB_LIST
struct Node; //不完整的声明,结构的定义在.c文件中
typedef struct Node* Head; //头结点的votes用来记人数
typedef struct Node* Person; //结点的votes用来记投票
#endif
Head Create( void );
Person AddVotes( char* PersonName, Head X );
void Print( Head X );
int PersonsNumbers( Head X);
//dblist.c
#include "dblist.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Node
{
char name[16];
int votes;
Person Ahead;
Person Next;
};
Head
Create( )
{
Head p;
p = malloc( sizeof( struct Node ) );
if( P == NULL )
{
printf( "Head创建时内存不足\n" );
exit( 1 );
}
strcpy( p->name, "a" );
p->votes = 0;
p-> Ahead = Next = NULL;
return p;
}
Head //如果表里有这个人就为这个人的票数加1,没有的话就插入一个结点,插入后整个表是排序好了的
AddVotes( char* PersonName, Head X )
{
Person p1, p2, p3;
int a;
p2 = X->Next;
p3 = X;
while( p2 != NULL )
{
a = strcmp( PersonName, p2->name );
if( a == 0 )
{
++p2->votes;
return X;
}
else
if( a > 0 )
{
p3 = p2;
p2 = p2->Next;
}
else
break;
}
p1 = malloc( sizeof( struct Node ) );
if( p1 == NULL )
{
printf( "Person创建时内存不足\n" );
exit( 1 );
}
strcpy( p1->name, PersonName );
p1->votes = 1; //因为这个不存在的人被投了一票
++X->votes; //表中人数加1
p1->Ahead = p3;
p1->Next = p2;
p3->Next = p1;
if( p2 != NULL )
p2->Ahead = p1;
return X;
}
void
Print( Head X )
{
Person p;
for( p = X->Next; p != NULL; p = p->Next )
printf( "%16s:%d\n", p->name, p->votes );
}
int //表中的人数
PersonsNumbers( Head X )
{
return X->votes;
}
|