这段代码中存在一个问题,它删除了 cur->calendar 链表中的所有内容,而不仅仅是条件中的那个
there is a problem in this code its deleting everything in cur->calendar linked list not just the one in the condition
我尝试了所有方法,但我不知道现在该怎么做,所以非常感谢您的帮助!
void DeleteAtPosition(Appointment* head, int pos) {
Appointment* cur = head->next;
Appointment* prev = head;
int i = 1;
if (isEmptylist(head)) {
cout << "LIST IS EMPTY" << endl;
}
if (pos == 0) {
delete head;
head = cur;
}
while (i < pos && cur->next != NULL) {
cur = cur->next;
prev = prev->next;
i++;
}
prev->next = cur->next;
delete cur;
}
void cancel(Company* c, string title) {
Employee* cur = c->head;
Appointment* curr=cur->Calendar;
int pos = 0;
while (cur != NULL) {
while (cur->Calendar != NULL) {
if (cur->Calendar->Title == title) {
DeleteAtPosition(curr, pos);
}
pos++;
cur->Calendar = cur->Calendar->next;
}
cur = cur->next;
}
}
我认为问题出在取消功能上,而不是删除功能上,但我不知道如何解决
问题是你在做cur->Calendar = cur->Calendar->next;
。您正在将原始指针移到列表上,因此在内部 while 循环的末尾,cur->Calendar
将变为 null
.
您应该改为使用 curr
变量来遍历列表,如下所示:
void cancel(Company* c, string title) {
Employee* cur = c->head;
int pos = 0;
while (cur != NULL) {
Appointment* curr=cur->Calendar; // reset curr pointer in every iteration
while (curr != NULL) { // use the curr pointer to go over the list
if (curr->Title == title) { // check the title of the current appointment with the "curr" pointer
DeleteAtPosition(cur->Calendar, pos); // use the original pointer as the head of the list for deletion
}
pos++;
curr = curr->next; // move the "curr" pointer to the next element of the list
}
cur = cur->next;
}
}
我尝试了所有方法,但我不知道现在该怎么做,所以非常感谢您的帮助!
void DeleteAtPosition(Appointment* head, int pos) {
Appointment* cur = head->next;
Appointment* prev = head;
int i = 1;
if (isEmptylist(head)) {
cout << "LIST IS EMPTY" << endl;
}
if (pos == 0) {
delete head;
head = cur;
}
while (i < pos && cur->next != NULL) {
cur = cur->next;
prev = prev->next;
i++;
}
prev->next = cur->next;
delete cur;
}
void cancel(Company* c, string title) {
Employee* cur = c->head;
Appointment* curr=cur->Calendar;
int pos = 0;
while (cur != NULL) {
while (cur->Calendar != NULL) {
if (cur->Calendar->Title == title) {
DeleteAtPosition(curr, pos);
}
pos++;
cur->Calendar = cur->Calendar->next;
}
cur = cur->next;
}
}
我认为问题出在取消功能上,而不是删除功能上,但我不知道如何解决
问题是你在做cur->Calendar = cur->Calendar->next;
。您正在将原始指针移到列表上,因此在内部 while 循环的末尾,cur->Calendar
将变为 null
.
您应该改为使用 curr
变量来遍历列表,如下所示:
void cancel(Company* c, string title) {
Employee* cur = c->head;
int pos = 0;
while (cur != NULL) {
Appointment* curr=cur->Calendar; // reset curr pointer in every iteration
while (curr != NULL) { // use the curr pointer to go over the list
if (curr->Title == title) { // check the title of the current appointment with the "curr" pointer
DeleteAtPosition(cur->Calendar, pos); // use the original pointer as the head of the list for deletion
}
pos++;
curr = curr->next; // move the "curr" pointer to the next element of the list
}
cur = cur->next;
}
}