道歉,如果這是一個愚蠢的/簡單的問題..但我很迷茫。我無法運行此程序。我編寫了這個程序來讀取2個值,第一個是鏈表中的一些元素,第二個是可以放入每個元素中的最大隨機值。讓mergesort工作在鏈表上?
然後它應該使用歸併排序算法來排序和重新打印排序列表。
好了,我得到這樣的錯誤:
base operand of `->' has non-pointer type `LIST'
和
request for member `element' in `conductor', which is of non-aggregate type `LIST *'
...(和其他一些)。
是的,這是一個類..我寫了程序,但我不知道我在這裏做錯了什麼或爲什麼我得到錯誤?任何幫助表示讚賞!謝謝
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <sys/time.h>
using namespace std;
typedef struct LIST {
int element;
LIST *next;
};
LIST split(LIST list)
{
LIST pSecondCell;
if (list == NULL)
return NULL;
else if (list.next == NULL)
return NULL;
else {
pSecondCell = list.next;
list.next = pSecondCell.next;
pSecondCell.next = split(pSecondCell->next);
return pSecondCell;
}
}
LIST merge(LIST list1, LIST list2)
{
if (list1 == NULL)
return list2;
else if (list2 == NULL)
return list1;
else if (list1.element <= list2.element) {
list1.next = merge(list1.next, list2);
return list1;
} else {
list2.next = merge(list1, list2.next);
}
}
LIST MergeSort(LIST list)
{
LIST SecondList;
if (list == NULL)
return NULL;
else if (list.next == NULL)
return list;
else {
SecondList = split(list);
return merge(MergeSort(list), MergeSort(SecondList));
}
}
int main(int argCount, char *argVal[])
{
int i, number, max;
struct timeval time1;
struct timeval time2;
//check for correct number of arguments
if (argCount != 3) {
cout << "Incorrect number of arguments" << endl;
return 0;
}
// initialize read in n and max values
number = atoi(argVal[1]);
max = atoi(argVal[2]);
// create list and fill with random numbers
LIST *conductor;
LIST *root = new LIST;
conductor = root;
for (i = 0; i < number; i++) {
conductor.element = rand() % max;
conductor.next = new LIST;
conductor = conductor.next;
}
// time how long it takes to sort array using mergeSort
gettimeofday(&time1, NULL);
mergeSort(root);
gettimeofday(&time2, NULL);
// print name, sorted array, and running time
cout << "Heather Wilson" << endl;
conductor = root;
for (i = 0; i < number - 2; i++) {
cout << conductor.element << ", ";
conductor = conductor.next;
}
double micro1 = time1.tv_sec * 1000000 + time1.tv_usec;
double micro2 = time2.tv_sec * 1000000 + time2.tv_usec;
cout << conductor.element << endl;
cout << "Running time: " << micro2 - micro1 << " microseconds" << endl;
return 0;
}
當從編譯器讀取錯誤輸出時,請務必查看發生錯誤的行*。這是一個非常強烈的暗示,你應該開始關注這條線,以及它的運作方式。另外,如果你找到了可以幫助你的答案,你應該接受它。你問過幾個問題,但我還沒有看到你接受任何問題。 –