数据结构之单链表操作
一、引入文件
#include <stdio.h>
#include <malloc.h>
二、定义结构体
struct ListNode {
int val;
struct ListNode* next;
};
三、初始化链表
void initList(struct ListNode* L)
{
//带头节点
L->next = NULL;
}
四、判断链表是否为空
bool isemptyList(struct ListNode* L)
{
//查找首元节点是否为空
if (L->next)return false;
else return true;
}
五、创建链表(带头节点)
void CreateList_tail(struct ListNode* L, Elemtype* a, int n)
{
struct ListNode* h;
h = L;//拷贝头指针
struct ListNode* s;
s = L->next;
//尾插法
for (int i = 0; i < n; i++) {
s = (struct ListNode*)malloc(sizeof(struct ListNode));
//尾插入节点
s->val = a[i];
s->next = h->next;
h->next = s;
//进入下一节点
h = s;
s = s->next;
}
}
六、输出链表
void printList(struct ListNode* L) {
printf("输出链表: ");
struct ListNode* p;
p = L->next;//跳过头结点到首元位置
while (p != NULL) {
printf("%c ", p->val);
p = p->next;
}
printf("\n");
}
七、查找元素
1.判断元素是否存在
bool isexistList(struct ListNode* L, int i)
{
int b = 0;
while (L) {
L=L->next;
b++;
if (b == i) {
return true;
}
}
if (b < i)return false;
}
2.如果存在则输出元素
void searchList(struct ListNode* L, int i, bool a)
{
if (a == true) {
int b = 0;
while (L) {
L=L->next;
b++;
if (b == i) {
printf("%c ", L->val);
}
}
}
}
八、主函数验证结果
void main()
{
Elemtype a[26] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z' };
struct ListNode* l1;
l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
initList(l1);
if (isemptyList(l1))printf("链表为空!\n");
else printf("链表为非空!\n");
CreateList_tail(l1, a, 26);
printList(l1);
searchList(l1, 4, isexistList(l1, 4));
}