你得到了兩個鏈表,事情是其中一個是排序的,另一個不是任務是你必須合并它們并對它們的值進行排序,同時在執行期間進行比較,而不是分別對兩個鏈表進行排序,也不使用任何內置來自 C 模板庫的方法。
我自己嘗試過這個問題,但它不起作用。我認為它正在接近 if 條件中的無限回圈條件!
這就是我所做的:
#include <iostream>
using namespace std;
struct Student {
int id;
Student *next = NULL;
};
Student *first = NULL;
Student *last = NULL;
Student *first2 = NULL;
Student *last2 = NULL;
void display(Student *k);
void insert_end(Student *k);
void merge();
int main() {
int exit = 1;
do {
cout << "11.Display, 12.Insert, 3.Merge\n";
cout << "21.Display, 22.Insert, 0:exit\n";
cin >> exit;
switch (exit) {
case 11:
display(first);
break;
case 12:
insert_end(last);
break;
case 3:
// first = mergeTwoLists(first, first2);
//merge();
Student* SortedMerge(Student* a, Student* b);
break;
case 21:
display(first2);
break;
case 22:
insert_end(last2);
break;
default:
cout << "WRONG\n";
break;
}
} while (exit != 0);
return 0;
}
void display(Student *k) {
Student *p = k;
while (p != NULL) {
cout << "ID: " << p->id << "\n";
p = p->next;
}
}
void insert_end(Student *k) {
cout << "This is the function of insert_end \n";
Student *current = new Student;
cout << "Enter ID: ";
cin >> current->id;
if (k == NULL) {
if (k == last) {
first = last = current;
} else {
first2 = last2 = current;
}
} else {
if (k == last) {
last->next = current;
last = current;
} else {
last2->next = current;
last2 = current;
}
}
}
void merge() {
Student *p1 = first;
Student *p2 = first2;
while (p1 != NULL) {
p2 = first2;
while (p2->next != NULL) {
if (p1->id <= p2->id) {
Student *curr = p2;
curr->next = p1->next;
p1->next = curr;
}
p2 = p2->next;
}
p1 = p1->next;
}
}
可能的優化解決方案是什么?
uj5u.com熱心網友回復:
您首先需要重寫函式insert_end。最初,指標 last 和 last2 都是空指標
Student *first = NULL;
Student *last = NULL;
Student *first2 = NULL;
Student *last2 = NULL;
因此,如果用戶首先決定填寫第二個串列,那么由于這個 if 陳述句
if (k == NULL) {
if (k == last) {
first = last = current;
} else {
first2 = last2 = current;
}
}
該函式將在第一個串列而不是第二個串列中插入一個新節點。
函式merge也是錯誤的。對于初學者來說,它既不改變也不first改變和。first2lastlast2
如果 if 陳述句
if (p1->id <= p2->id) {
Student *curr = p2;
curr->next = p1->next;
p1->next = curr;
}
給出控制然后next指標的資料成員p2由于這些行而改變
Student *curr = p2;
curr->next = p1->next;
即next第二個串列的指標的資料成員指向第一個串列的節點。
但是在 if 陳述句之后
p2 = p2->next;
指標p2指向第一個串列中的節點,而不是指向第二個串列中的節點。
為了讓生活更輕松,您需要再定義一個結構,例如
struct List
{
struct Student *first;
struct Student *last;
};
并為這種結構型別的指標定義函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443092.html
下一篇:如何檢查無效地址/已洗掉指標?
