题解 | #记票统计#
记票统计
https://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct people{
char* name;
int ticket;
struct people* next;
};
//使用链表的形式存储候选人
int main() {
int n, m, invaild = 0;
struct people head; //创建链表头
char name[100];
struct people* cur = &head; //链表当前指针
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%s", name); //获取候选人名字
struct people *tmp = (struct people*)malloc(sizeof(struct people)); //动态申请节点
tmp->name = (char*)malloc(sizeof(char)*100); //为节点的候选人名称申请空间
strcpy(tmp->name, name); //候选人名称赋值
tmp->ticket = 0, tmp->next = NULL; //初始节点
cur->next = tmp; //将新节点加入链表
cur = cur->next;
}
scanf("%d", &m);
for(int i=0; i<m; i++){
scanf("%s", name); //获取投票信息
cur = head.next; //cur指向链表第一个节点
while(cur){ //遍历链表
if(strcmp(name, cur->name) == 0){//找到对应的候选人,
cur->ticket++; //票数加1
break; //跳出循环
}
cur = cur->next;
}
if(!cur)invaild++; //找不到对应候选人,不合法票数+1
}
cur = head.next;
for(int i=0; i<n; i++){
printf("%s : %d\n", cur->name, cur->ticket);
cur = cur->next;
}
printf("Invalid : %d", invaild);
return 0;
}
查看12道真题和解析