当我运行这些方法时,我的列表永远不会增长,我也不知道为什么。头尾总是相等的。我的指针或结构设置有问题吗?我花了 4 个小时在这个切换东西上,我似乎无法找到为什么事情不工作,除非它是一个指针的东西(我正在学习并且不擅长)..
typedef struct EmployeeStruct
{
char LastName[10];
char FirstName[10];
struct EmployeeStruct *next;
} Employee;
struct EmployeeStruct *head,*tail, *temp;
Employee* hireEmployee(Employee* head, char LastName[10], char FirstName[10])
{
// exit if max number of employees is reached
if(eNum > MAX_EMPLOYEES)
{
printf("Sorry, but you can't hire any more employees right now\n");
return 0;
}
// insert at tail
newHire = head;
while(newHire->next != NULL)
{
newHire = newHire->next;
printf("nope\n");
}
// allocate memory
newHire->next = malloc(sizeof(Employee));
if(newHire == NULL)
{
printf("Memory allocation failed");
return 0;
}
newHire->next = NULL;
// insert values into this node
strcpy(newHire->LastName, LastName );
strcpy(newHire->FirstName, FirstName );
newHire->EmployeeNumber = eNum;
tail = newHire;
//printf("%d\n",newHire->EmployeeNumber);
eNum+=1;
//printf("%d\n",newHire->EmployeeNumber);
return newHire;
}
int main()
{
char choice;
char first[20];
char last[20];
int i = 0;
// allocate memory
head = malloc(sizeof(Employee));
if(head == NULL)
{
printf("Memory allocation failed");
return 0;
}
head->next = tail;
while(TRUE)
{
// prompt user for choice
printf("Please choose from the following options:\n");
printf("a: Hire new employee\nb: Promote employee\nc: Delete employee\nd: Display roster\ne: Exit\n");
scanf("\n%c", &choice);
switch(choice)
{
case 'a':
printf("New employees first name:\n");
scanf("%s", first);
printf("New employees last name:\n");
scanf("%s", last);
tail = hireEmployee(head,last,first);
temp = head;
while(temp->next != NULL)
{
temp = temp->next;
printf("nope\n");
}
temp->next = tail;
tail = temp->next;
printf("A%d: %s %s\n", tail->EmployeeNumber,tail->FirstName,tail->LastName);
tail = tail->next;
printf("A%d: %s %s\n", tail->EmployeeNumber,tail->FirstName,tail->LastName);
tail->next = NULL;
//printEmployees(head);
break;
case 'b':
//TBD
break;
}
}
}
** 现在可以工作了,是这四个错误:
(newHire == NULL)
(head == NULL)
newHire =newHire->next;
temp->next = tail;
顺便说一句,我总是做作业和上课,而我只是被困在一个更大的程序的一小部分。因此,感谢那些没有侮辱我并实际上提供了有用建议的人。我真的很感激。