当试图在具有两个节点的链接列表上运行两次deleteLast()函数(以获取一个空列表)时,我遇到了问题。代码可以编译并运行,但是当我在空的链表上调用traverse()时,会遇到一个无限的while循环,而我无法确定原因。
奇怪的是,如果我两次调用deleteFirst()而不是deleteLast(),程序将正常运行并终止。
下面是我的方法的代码:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <time.h>
struct NODE
{
struct NODE *link;
int value;
};
typedef struct NODE Node;
/* Deletes the first item in the list and returns next item */
Node *deleteFirst(Node **ptrToHeadPtr)
{
Node *current;
// If list is empty do nothing
if (*ptrToHeadPtr == NULL)
return NULL;
else
{
current = *ptrToHeadPtr;
*ptrToHeadPtr = current->link;
free(current);
}
return *ptrToHeadPtr;
}
/* Inserts a new Node to the end of the list and returns it */
Node *insertLast(Node **ptrToHeadPtr, int val)
{
Node *current, *lastNode;
lastNode = (Node *)malloc( sizeof (Node) );
// Check if malloc was successful
if(!lastNode) return NULL;
lastNode->value = val;
lastNode->link = NULL;
if (*ptrToHeadPtr == NULL)
*ptrToHeadPtr = lastNode;
else
{
current = *ptrToHeadPtr;
// Walk to the end of the list
while(current->link != NULL)
current = current->link;
// Insert new item at the end of the list
current->link = lastNode;
}
return lastNode;
}
/* Deletes the last Node in the list and returns*/
Node *deleteLast(Node **ptrToHeadPtr)
{
Node *current, *previous;
/* If list is empty do nothing */
if (*ptrToHeadPtr == NULL)
return NULL;
current = *ptrToHeadPtr;
previous = NULL;
/* If list has one item delete it and return NULL */
if (current->link == NULL)
{
*ptrToHeadPtr == NULL;
free(current);
return NULL;
}
else
{
/* Walk to the end of the list */
while (current->link != NULL)
{
previous = current;
current = current->link;
}
previous->link = NULL;
free(current);
return previous;
}
}
/* Traverses the list, printing the value of each Node */
void traverse(Node*p)
{
while( p!= NULL )
{
printf("%d ",p->value);
p=p -> link;
}
}
/* Walks through the linked list, freeing memory of each Node */
void freeList(Node *p)
{
Node *temp;
while( p != NULL )
{
temp = p;
p = p-> link;
free(temp);
}
}
int main()
{
Node *headPtr = NULL;
insertLast( &headPtr, 33 );
insertLast( &headPtr, 35 );
traverse(headPtr);
printf("\n");
deleteFirst ( &headPtr );
traverse(headPtr);
printf("\n");
deleteLast ( &headPtr );
traverse(headPtr);
freeList(headPtr);
return 1;
}
最佳答案
在您的deleteLast()函数中(它们在C中被称为函数,仅是您所知道的,而不是方法。不要试图听起来很笨拙。)
/* If list has one item delete it and return NULL */
if (current->link == NULL)
{
*ptrToHeadPtr == NULL; // CHANGE THIS TO =, NOT ==
free(current);
return NULL;
}
编辑:就像上面的海报所建议的那样,您绝对应该使用-Wall进行编译(W区分大小写,必须大写)。