我正在尝试测试我创建的链接列表ADT。但是,每当我尝试测试我的ADT时,它都没有创建列表,我不明白为什么?,目前,我们使用的是dummyNode方法而不是将第一个元素作为列表的头部。它与我的ADT有关吗?
node*createList()
{
node*dummyNode;
dummyNode = malloc(sizeof(node)*101);
dummyNode->next = NULL;
return dummyNode;
}
node*addFront(node*list, int toBeAdded)
{
node*newNode;
newNode = initNode(toBeAdded);
newNode->next = list->next;
list->next = newNode;
return newNode;
}
void printList(node*theHead)
{
node*currentPosition;
currentPosition = theHead->next;
while(currentPosition != NULL)
{
printf("This is the value of the current node : %d\n",currentPosition->nodeValue);
currentPosition= currentPosition->next;
}
}
node*initNode(int getValue)
{
node*newNode;
newNode = malloc(sizeof(node)*101);
newNode->nodeValue = getValue;
newNode->next = NULL;
return newNode;
}
void destroyList(node*theList)
{
node*temp;
theList->nodeValue = 0;
while(theList->next != NULL)
{
temp = theList->next;
free(theList);
theList=temp;
}
}
node*removeFromFront(node*theList)
{
node*temp;
if(theList==NULL)
{
return NULL;
}
temp=theList->next;
theList->next=NULL;
return temp;
}
int listLength(node*theHead)
{
int length;
length=0;
while(theHead != NULL)
{
length++;
theHead = theHead ->next;
}
return length;
}
and this is my test.c
node*testData;
int length,i;
int myArray[5] = {1,2,3,4,5};
testData = createList();
length = listLength(testData);
for(i=0; i<length; i++)
{
testData = addFront(testData, myArray[i]);
printList(testData);
}
This is the struct
struct listNode
{
int nodeValue;
struct listNode * next;
};
typedef struct listNode node;
node*createList();
node*addFront(node*theHead, int toBeAdded);
void printList(node*theHead);
node*initNode(int getValue);
void destroyList(node*theList);
node*removeFromFront(node*theList);
int listLength(node*theHead);
答案 0 :(得分:1)
你的实施没问题,问题是你的test.c
首先,如前所述,将您的分配更改为:
malloc(sizeof(node));
接下来你的test.c应该是:
int main() {
node*testData;
int length,i;
int myArray[5] = {1,2,3,4,5};
testData = createList();
for(i=0; i<5; i++)
{
addFront(testData, myArray[i]);
}
printList(testData);
destroyList(testData);
return 0;
}
这应打印预期结果:
This is the value of the current node : 5
This is the value of the current node : 4
This is the value of the current node : 3
This is the value of the current node : 2
This is the value of the current node : 1
答案 1 :(得分:0)
使用您创建的测试跟踪您的功能。您应该在addToFront()函数中发现问题。主要是 newNode->next = list->next;
行。
一旦您发现了问题并解决了它,请再次尝试您的测试。你的指针逻辑有点偏。
另外,另外,malloc(sizeof(node)* 101)分配的内存比需要的多得多,它只比malloc(sizeof(node))好得多