2つのノードを持つリンクリストでmy deleteLast()関数を2回実行して空のリストを取得しようとすると、問題が発生しています。コードがコンパイルされて実行されますが、空のリンクリストでtraverse()を呼び出すと、whileループが無限になり、理由を判断できません。ANSI C S-Linked List - 正しく動作していない
奇妙なことに、私がdeleteLast()の代わりにdeleteFirst()を2回呼び出すと、プログラムが実行され、正しく終了します。あなたの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;
}
正しいタグを追加してください。 'C'タグはC89/90ではなく標準Cのタグです。 [ask]を読んで[mcve]を入力してください。私たちはデバッグサービスはありません。 – Olaf
すべての警告を有効にしてコンパイルし(gccまたはclangの場合は '-Wall')、すべての警告を修正します。 – user3386109