创建结构体
struct Node
{
int data;
struct Node* Next;
};
创建头节点
struct Node* CreateHeadNode()
{
struct Node* HeadNode = (struct Node*)malloc(sizeof(struct Node));
assert(HeadNode);
HeadNode->Next = NULL;
return HeadNode;
}
创建节点
struct Node* CreateNode(int data)
{
struct Node* NewNode = (struct Node*)malloc(sizeof(struct Node));
assert(NewNode);
NewNode->data = data;
NewNode->Next = NULL;
return NewNode;
}
头插法
void InsertByHead(struct Node* HeadNode, int data)
{
struct Node* NewNode = CreateNode(data);
NewNode->Next = HeadNode->Next;
HeadNode->Next = NewNode;
}
尾插法
void InsertByTail(struct Node* HeadNode, int data)
{
struct Node* Temp = HeadNode;
struct Node* NewNode = CreateNode(data);
while (Temp->Next != NULL)
{
Temp = Temp->Next;
}
Temp->Next = NewNode;
NewNode->Next = NULL;
}
头删法
void DeleteByHead(struct Node* HeadNode)
{
struct Node* PreNode = HeadNode;
struct Node* CurNode = HeadNode->Next;
PreNode->Next = CurNode->Next;
free(CurNode);
CurNode = NULL;
}
尾删法
void DeleteByTail(struct Node* HeadNode)
{
struct Node* PreNode = HeadNode;
struct Node* CurNode = HeadNode->Next;
while (CurNode->Next != NULL)
{
PreNode = CurNode;
CurNode = PreNode->Next;
}
PreNode->Next = NULL;
free(CurNode);
CurNode = NULL;
}