So I am writing a program where the user has to enter various names , and then a list shows the entered names in alphabetical order. My program is working , but if for example the user enters the same name twice , it is showing twice in the list. How can I introduce a counter , so that for example if the user enters Mark,Mark,Alan, Paul , it shows as :
Alan 1
Mark 2
Paul 1
This is the code I have written so far :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student Student;
struct student
{
char name[50];
int counter;
Student *next;
};
void insertStudent(Student** listHead, Student* pStudent)
{
Student *prevNode = NULL, *curNode = *listHead;
Student *newNode = (Student*) malloc(sizeof(Student));
memcpy(newNode, pStudent, sizeof(Student));
newNode->next = NULL;
while ((curNode != NULL) && (strcmp(newNode->name, curNode->name) > 0))
{
prevNode = curNode;
curNode = prevNode->next;
}
if (prevNode == NULL)
*listHead = newNode;
else
prevNode->next = newNode;
newNode->next = curNode;
}
void readStudent(Student* pStudent)
{
printf("Enter name: ");
scanf("%s", pStudent->name);
}
void displayStudent(const Student* pStudent)
{
printf("%s\n", pStudent->name);
}
void printStudents(Student* listHead)
{
Student* curNode = listHead;
printf("---------------------------\n");
while (curNode != NULL)
{
displayStudent(curNode);
curNode = curNode->next;
}
}
void destroyList(Student** listHead)
{
Student* curNode = *listHead;
Student* prevNode = NULL;
while (curNode != NULL)
{
prevNode = curNode;
curNode = curNode->next;
free(prevNode);
}
*listHead = NULL;
}
int menu()
{
int choice = 0;
do
{
printf("1. Add new student\n");
printf("2. Display Student List\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
}
while ((choice < 1) || (choice > 3));
return choice;
}
void addNewStudent(Student **listHead)
{
Student student = {0};
readStudent(&student);
displayStudent(&student);
insertStudent(listHead, &student);
}
int main()
{
int choice = 0;
Student* listHead = NULL;
do
{
choice = menu();
switch (choice)
{
case 1:
addNewStudent(&listHead);
break;
case 2:
printStudents(listHead);
break;
case 3:
destroyList(&listHead);
break;
default:
break;
}
}
while (choice != 4);
destroyList(&listHead);
}