#include <iostream> #include <ctime> using namespace std; struct student int id; char gender; student*next; }; void twoQueue(student*hybrid,student*&girls,student*&boys); void output(student*girls,student*boys); int main() { int num; cin >num; student*hybrid=NULL,*hybridCur NULL,*tmp; for (int i=0;i<num;i++) tmp new student; cin >tmp->id >tmp->gender; tmp->next NULL; if (hybridCur =NULL) hybridCur tmp; hybrid hybridCur; else hybridCur->next =tmp; hybridCur hybridCur->next; student*girls NULL,boys NULL; twoQueue(hybrid,girls,boys); output(girls,boys); return 0; } void twoQueue(student*hybrid,student*&girls,student*&boys){ } 请实现twoQuene函数,功能是根据学生性别,将学生链表拆分成女生链表和男生链表。
时间: 2023-08-08 09:04:31 浏览: 109
好的,下面是根据学生性别将学生链表拆分成女生链表和男生链表的twoQueue函数的实现:
```c++
void twoQueue(student* hybrid, student*& girls, student*& boys) {
student* p_girls = NULL, * p_boys = NULL;
while (hybrid != NULL) {
// 如果是女生,插入到女生链表中
if (hybrid->gender == 'F') {
if (girls == NULL) {
girls = hybrid;
p_girls = girls;
}
else {
p_girls->next = hybrid;
p_girls = p_girls->next;
}
}
// 如果是男生,插入到男生链表中
else if (hybrid->gender == 'M') {
if (boys == NULL) {
boys = hybrid;
p_boys = boys;
}
else {
p_boys->next = hybrid;
p_boys = p_boys->next;
}
}
hybrid = hybrid->next;
}
// 需要将两个链表的最后一个节点的next指针置为NULL
if (p_girls != NULL) {
p_girls->next = NULL;
}
if (p_boys != NULL) {
p_boys->next = NULL;
}
}
```
该函数首先定义两个指针p_girls和p_boys,分别表示女生链表和男生链表的尾节点,初始值都为NULL。然后遍历学生链表,如果是女生,则将该节点插入到女生链表中,如果是男生,则将该节点插入到男生链表中。插入操作需要更新p_girls和p_boys的值,使它们指向链表的最后一个节点。最后,需要将两个链表的最后一个节点的next指针置为NULL,以保证链表的正确性。
阅读全文