#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
typedef struct Node
{
int value;
struct Node* next;
}Node;
//创建表头
Node* CreateList()
{
Node* head = (Node*)calloc(1, sizeof(Node));
if (head == NULL)
{
exit(EXIT_FAILURE);
}
return head;
}
//创建节点
Node* CreateNode(int val)
{
Node* node = (Node*)calloc(1, sizeof(Node));
if (node == NULL)
{
exit(EXIT_FAILURE);
}
node->value = val;
node->next = NULL;
return node;
}
//往头添加节点
void PushFront(Node** list, int val)
{
if (!*list)return;
Node* node = CreateNode(val);
Node* cur = *list;
node->next = cur->next;
cur->next = node;
}
void PushBack(Node* list, int val)
{
if (!list)return;
Node* node = CreateNode(val);
Node* cur = list->next;
while (cur->next)
{
cur = cur->next;
}
cur->next = node;
node->next = NULL;
}
//指定位置插入
void InsertIndex(Node* list, int index, int val)
{
if (!list)return;
Node* cur = list;
index--;
while (index-- && cur->next)
{
cur = cur->next;
}
if (!cur)
{
printf("超出插入范围\n");
}
else
{
Node* node = CreateNode(val);
node->next = cur->next;
cur->next = node;
}
}
//往头弹出节点
void PopFront(Node** list)
{
if (!*list)return;
Node* cur = *list;
Node* front = cur->next;
if (front)
{
cur->next = front->next;
free(front);
front = NULL;
}
}
void PopBack(Node** list)
{
if (!*list)
return;
Node* prenode = *list;
Node* curnode = prenode->next;
if (curnode)
{
while (curnode->next)
{
prenode = curnode;
curnode = curnode->next;
}
free(curnode);
prenode->next = NULL;
curnode = NULL;
}
}
//删除val节点
void EraseList(Node* list, int val)
{
if (!list)return;
Node* prenode = list;
Node* curnode = list->next;
while (curnode->next && curnode->value != val)
{
prenode = curnode;
curnode = curnode->next;
}
if (curnode->next && curnode)
{
prenode->next = curnode->next;
free(curnode);
curnode = NULL;
}
}
//查找val节点
bool SearchList(Node* list, int val)
{
if (!list)return false;
Node* cur = list->next;
while (cur->next)
{
if (cur->value == val)
{
return true;
}
cur->next;
}
}
//销毁链表
void DestoryList(Node** list)
{
if (!list)return;
Node* cur = *list;
while (cur->next)
{
PopFront(&cur);
}
free(*list);
*list = NULL;
}
void PrintList(Node* list)
{
if (list == NULL)
{
printf("The list is NULL\n");
return;
}
Node* cur = list->next;
while (cur)
{
printf("%d\t", cur->value);
cur = cur->next;
}
printf("\n");
}
void test()
{
Node* list = CreateList();
PushFront(&list, 1);
PushFront(&list, 2);
PushFront(&list, 3);
PushFront(&list, 4);
PushBack(list, 89);
PrintList(list);
//InsertIndex(list,2,66);
PopFront(&list);
PopBack(&list);
EraseList(list, 3);
PrintList(list);
DestoryList(&list);
PrintList(list);
}
int main()
{
test();
return 0;
}
有头链表和基本操作
最新推荐文章于 2024-07-10 22:22:07 发布