#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
//链表类型声明
struct Node
{
int element;
struct Node* next;
};
//创建表头(哑结点)
struct Node*createHeaderNode()
{
struct Node* p;
p = (Node*)malloc(sizeof(struct Node));
if (p == NULL)
{
printf("分配内存失败\n");
exit(1);
}
p->next = NULL;
return p;
}
//从表的头部插入
void insertFirst(struct Node* header, int x)
{
struct Node* tmp;
tmp = (Node*)malloc(sizeof(struct Node));
if (tmp == NULL)
{
printf("内存空间不足\n");
return;
}
tmp->element = x;
tmp->next = header->next;
header->next = tmp;
}
//从表的尾部插入
void insertLast(struct Node* header, int x)
{
struct Node* p;
struct Node* tmp;
tmp = (Node*)malloc(sizeof(struct Node));
if (tmp == NULL)
{
printf("内存空间不足\n");
return;
}
tmp->element = x;
tmp->next = NULL;
p = header;
while (p->next != NULL)
{
p = p->next;
}
p->next = tmp;
}
//查找表中结点值
struct Node* find(struct Node* header, int x)
{
struct Node* p;
p = header->next;
while (p != NULL && p->element != x)
{
p = p->next;
}
return p;
}
//查找表中结点位置操作
struct Node* findKth(struct Node* header, int position)
{
int count = 1;
struct Node* p;
if (position <= 0)
{
printf("position不能为0或负数\n");
return NULL;
}
p = header->next;
while (p != NULL)
{
if (count == position)
{
return p;
}
p = p->next;
count++;
}
return NULL;
}
//删除表中的结点值
void Delete(struct Node* header, int x)
{
struct Node* privious;
struct Node* p;
privious = header;
p = header->next;
while (p != NULL)
{
if (p->element == x)
{
privious->next = p->next;
free(p);
break;
}
else
{
privious = p;
p = p->next;
}
}
}
//判断表是否为空表
bool isEmpty(struct Node* header)
{
return header->next == NULL;
}
//打印表中结点个数,即表的大小
int size(struct Node* header)
{
int count = 0;
struct Node* p;
p = header->next;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
//打印表中的结点数据
void printList(struct Node* header)
{
struct Node* p;
p = header->next;
while (p != NULL)
{
printf("node element=%d\n", p->element);
p = p->next;
}
}
//主函数
int main(void)
{
struct Node* node;
struct Node* header;
//创建表头(哑结点)
header = createHeaderNode();
//判断表是否为空表
printf("List isEmpty?:%d\n", isEmpty(header));
printf("=======================\n");
//从表的头部插入
insertFirst(header, 1);
insertFirst(header, 2);
//打印表中的结点数据
printList(header);
printf("=======================\n");
//从表的尾部插入
insertLast(header, 3);
insertLast(header, 4);
//打印表中的结点数据
printList(header);
printf("=======================\n");
//判断表是否为空表
printf("List isEmpty?:%d\n", isEmpty(header));
printf("=======================\n");
//查找表中结点值
node = find(header, 3);
if (node == NULL)
{
printf("not find...\n");
}
else
{
printf("find node element: %d\n", node->element);
}
//查找表中结点位置操作
node = findKth(header, 2);
if (node == NULL)
{
printf("not find...\n");
}
else
{
printf("find node element: %d\n", node->element);
}
//删除表中的结点值
Delete(header, 3);
printList(header);
printf("=======================\n");
//打印表中结点个数,即表的大小
printf("List size:%d\n", size(header));
printf("=======================\n");
}