我编写了这个函数来删除单链表的最后一个节点。
问题是,它能够删除除第一个/起始节点之外的所有节点。
此代码片段缺少什么?
请回答我的特殊问题。
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char CharContent;
struct Node * NextNodePointer;
};
typedef struct Node Node;
#pragma region Prototypes
Node * CreateNewNode(char ch);
Node * AddNode(Node * start, Node * newNode);
void DeleteTailNode(Node * start);
void PrintAllNodes(const Node * start);
#pragma endregion Comments
main()
{
Node * start = NULL;
Node * newNode = NULL;
start = AddNode(start, CreateNewNode('A'));
start = AddNode(start, CreateNewNode('B'));
start = AddNode(start, CreateNewNode('C'));
start = AddNode(start, CreateNewNode('D'));
PrintAllNodes(start);
DeleteTailNode(start);
PrintAllNodes(start);
DeleteTailNode(start);
PrintAllNodes(start);
DeleteTailNode(start);
PrintAllNodes(start);
DeleteTailNode(start);
PrintAllNodes(start);
DeleteTailNode(start);
PrintAllNodes(start);
getch();
}
#pragma region Node * CreateNewNode(char ch)
Node * CreateNewNode(char ch)
{
struct Node * newNode = (struct Node *) malloc(sizeof(struct Node *));
newNode->CharContent = ch;
newNode->NextNodePointer = NULL;
return newNode;
}
#pragma endregion Comment
#pragma region UnifiedAddNode()
Node * AddNode(Node * start, Node * newNode)
{
Node * copyOfStart = start;
if(start == NULL)
{
return newNode;
}
else
{
while(copyOfStart->NextNodePointer != NULL)
{
copyOfStart = copyOfStart->NextNodePointer;
}
copyOfStart->NextNodePointer = newNode;
return start;
}
}
#pragma endregion Comment
void DeleteTailNode(Node * start)
{
Node * prev = NULL;
Node * current = start;
while(current->NextNodePointer != NULL)
{
prev = current;
current = current->NextNodePointer;
}
free (current);
if (prev != NULL)
{
prev->NextNodePointer = NULL;
}
}
#pragma region PrintAllNodes()
void PrintAllNodes(const Node * start)
{
struct Node * tempRoot = start;
while(tempRoot != NULL)
{
printf("%c, ", tempRoot->CharContent);
tempRoot = tempRoot->NextNodePointer;
}
printf("\n");
}
#pragma endregion Comment