线性表实践-选票算法

/*
选票系统,输入每个候选人的得票结果(采用单链表存放选票,候选人编号依次123...N,且每张选票只选一人)。
*/

/* 
单链表存放选票,每个节点的data域存放该选票所选的候选人,用一个数组a统计得票结果。
 */
 
typedef int Elemtype;

typedef struct linknode
{
    Elemtype data;
    struct linknode *next;
}Lnode;

Lnode *create()
{
    Elemtype d;
    Lnode h=NULL,*s,*t;
    int i=1;
    printf("创建一个单链表
");
    while(1)
    {
        printf("输入第%d节点data域值:",i);
        scanf("%d",&d);
        if(d==0)
        break;
        if(i==1)
        {
            h=(Lnode*)malloc(sizeof(Lnode));
            h->data=d;
            h->next=NULL;
            t=h;
        }
        else
        {
            s=(Lnode*)malloc(sizeof(Lnode));
            s->data=d;
            s->next=NULL;
            t->next=s;
            t=s;
        }
        i++;
    }
    return h;
}

void sat(Lnode* h,int a[])
{
    Lnode*p=h;
    while(p!=NULL)
    {
        a[p->data]++;
        p=p->next;
    }
}
 
 void main()
 {
    int a[N+1];
    for(i=0;i<N;i++)
        a[i]=0;
        Lnode*head;
        head=create();
        sat(head,a);
        printf("候选人:");
        for(i=1;i<N;i++)
            printf("%3d",i);
            printf("得票数:");
            for(i=1;i<=N;i++)
                printf("%3d",a[i]);
            printf("
");
 }
原文地址:https://www.cnblogs.com/pengjunwei/p/3724467.html