效果
代码
#include "stdio.h"
#include "stdlib.h"
typedef struct linknode {
int data;
struct linknode* next;
}LinkNode;
LinkNode* CreateHeadNode(void);//创建头结点
void CreateNewNode(LinkNode* H);//创捷节点
void PrintList(LinkNode* H);//打印链表
void DeleteNode(LinkNode* H, int data);//删除节点
void ReverseList(LinkNode* H);//反转链表
void function(LinkNode* H, int func);//功能汇总函数
int main()
{
LinkNode* H = CreateHeadNode();
int func;
while (1)
{
printf("Select function: ");
scanf_s("%d", &func);
function(H, func);
printf("\n");
}
return 0;
}
LinkNode* CreateHeadNode(void)
{
LinkNode* Head = (LinkNode*)malloc(sizeof(LinkNode));
//Head->num = 0;
Head->data = 0;
Head->next = NULL;
return Head;
}
void CreateNewNode(LinkNode* H)
{
int data;
LinkNode* ptr = (LinkNode*)malloc(sizeof(LinkNode));
ptr->next = H->next;
H->next = ptr;
scanf_s("%d", &data);
ptr->data = data;
H->data++;
}
void PrintList(LinkNode* H)
{
LinkNode* ptr = H->next;
printf("List: ");
while (ptr != NULL)
{
printf("%d\t", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
void DeleteNode(LinkNode* H, int data)
{
LinkNode* ptr = H->next;
LinkNode* ptr_last = H;
while (ptr != NULL && ptr->data != data)//先判空,否则会造成溢出
{
ptr_last = ptr;
ptr = ptr->next;
}
if (ptr != NULL && ptr->data == data)//上述两个条件有一个不符合就会进入if判断,所以此处仍要对两个条件判断
{
ptr_last->next = ptr->next;
free(ptr);
printf("delete successed\n");
}
else
printf("delete failed\n");
}
void ReverseList(LinkNode* H)
{
LinkNode* ptr = H->next;
LinkNode* ptr_last = NULL;
H->next = NULL;
while (ptr != NULL)
{
ptr_last = ptr;
ptr = ptr->next;
ptr_last->next = H->next;
H->next = ptr_last;
}
}
void function(LinkNode* H, int func)
{
switch (func)
{
case 1:
printf("ADD\n");
printf("data: ");
CreateNewNode(H);
break;
case 2:
printf("DEL\n");
printf("data: ");
int data;
scanf_s("%d", &data);
DeleteNode(H, data);
break;
case 3:
printf("PRT\n");
PrintList(H);
break;
case 4:
printf("REV\n");
ReverseList(H);
break;
default:
printf("ERR\n");
break;
}
}
标签:LinkNode,void,next,链表,基本功能,printf,data,ptr,指针
From: https://blog.csdn.net/yuzexuan666/article/details/136824114