C语言带头节点的单链表
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Lnode {
int data;
struct Lnode* next;
} Lnode, *linklist;
//带头节点的单链表的初始化
void initSingleLink(linklist* head) {
*head = (Lnode*)malloc(sizeof(Lnode));
(*head)->data = NULL;
(*head)->next = NULL;
}
//头插法
void insertHead(Lnode* head,int e) {
Lnode* node = (Lnode*)malloc(sizeof(Lnode));
node->data = e;
node->next = head->next;
head->next = node;
}
//尾插法
void inserttail(Lnode* head, int e) {
Lnode* node = (Lnode*)malloc(sizeof(Lnode));
node->data = e;
node->next = NULL;
Lnode* p = head;
while (p->next)
{
p= p->next;
}
p->next = node;
}
//删除元素为e的的节点
void delete(Lnode* head, int e) {
Lnode* p = head->next;
Lnode* q = head;
while (p)
{
if (p->data == e)
{
if (!p->next)
{
free(p);
q->next = NULL;
return;
}
else
{
q->next = p->next;
free(p);
return;
}
}
q = p;
p = p->next;
}
}
//删除第index的节点
void deleteIndex(Lnode* head, int index, int* e) {
int i = 0;
Lnode* p = head->next;
Lnode* q = head;
while (p)
{
if (i == index)
{
*e = p->data;
if (p->next)
{
q->next = p->next;
free(p);
}
else
{
q->next = NULL;
free(p);
}
return true;
}
q = p;
p = p->next;
i++;
}
return false;
}
//链表的遍历
void show(Lnode* head) {
if (!head->next)
{
printf("链表为空\n");
return;
}
Lnode* p = head->next;
int i = 0;
while (p)
{
printf("链表中第%d个元素是%d\n", i++, p->data);
p = p->next;
}
}
// 获取链表中节点的个数
int getSize(Lnode* head) {
int i = 0;
Lnode* p = head->next;
while (p)
{
p = p->next;
i++;
}
return i;
}
//链表的逆序
Lnode* reversedAtNode(linklist* head, Lnode* pnode) {
if (pnode->next == NULL)
{
(* head)->next = pnode;
}
else
{
(reversedAtNode(head, pnode->next))->next = pnode;
pnode->next = NULL;
}
return pnode;
}
void reversed(Lnode* head) {
if (!head || !(head->next))
{
return;
}
reversedAtNode(&head, head->next);
}
void main() {
linklist head;
initSingleLink(&head);
//测试头插法
printf("测试头插法===\n");
for (int i = 0; i < 5; i++)
{
insertHead(head, i);
}
show(head);
//测试尾插法
printf("测试尾插法===\n");
for (int i = 5; i < 10; i++)
{
inserttail(head, i);
}
show(head);
//测试删除
printf("测试删除元素为e的节点\n");
delete(head, 9);
show(head);
printf("测试删除元素为e的节点====end\n");
//测试删除第index位置的节点
printf("测试删除第index位置的节点\n");
int res;
deleteIndex(head, 8, &res);
show(head);
printf("删除的元素是%d\n", res);
printf("测试删除第index位置的节点=====end\n");
printf("链表中共有%d个元素\n", getSize(head));
//测试链表的逆序
printf("测试带头节点的单链表的逆序\n");
reversed(head);
show(head);
printf("测试带头节点的单链表的逆序====end\n");
}