C语言,单链表, 增,删, 查, 判空,打印,计算长度操作
# include <stdio.h>
# include <stdlib.h>
// 定义结构体
typedef struct Node{
int data;
struct Node *next;
}Node, *NodeList;
// 初始化
bool InitList(NodeList &L) {
L = (Node *)malloc(sizeof(Node *));
L->data = NULL;
L->next = NULL;
if (L!=NULL) {
return true;
}else {
return false;
}
}
// 添加10个元素
void addList(NodeList &L) {
Node *end = L;
for (int i=0;i<10;i++) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = i;
p->next = NULL;
end->next = p;
end = p;
}
}
// 输出链表
void putList(NodeList L) {
Node *p = L->next;
while (p!=NULL) {
printf(" %d -> ", p->data);
p = p->next;
}
}
// 查询指定元素的前驱结点
Node * look_i(NodeList L, int i) {
int j = 0;
Node *p = L;
while (p!=NULL && j<i-1) {
p = p->next;
j++;
}
return p;
}
// 在指定位序位置插入元素e
bool InsertList(NodeList &L, int i, int e) {
if (i<1) {
return false;
}else {
Node *p = look_i(L, i);
if (p==NULL) {
return false;
}else {
Node *s = (Node *)malloc(sizeof(Node));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
}
}
// 在指定位序位置删除元素, 返回元素e值
bool DeleteList(NodeList &L, int i, int &e){
if (i<1) {
return false;
}else {
Node *p = look_i(L, i);
if (p==NULL) {
return false;
}else {
Node *s = p->next;
e = s->data;
p->next = s->next;
free(s);
return true;
}
}
}
// 判断空表
bool empty(NodeList L) {
if (L->next == NULL) {
return true;
}else {
return false;
}
}
// 计算表长度
int Length(NodeList L) {
int j = 0;
Node *p = L->next;
while (p!=NULL) {
p = p->next;
j++;
}
return j;
}
// 主函数
int main() {
NodeList L;
InitList(L);
printf("\n 判断空表 \n");
if (empty(L)) {
printf("\n 是空表 \n");
}else {
printf("\n 非空表 \n");
}
printf(" 表长度:%d ", Length(L));
// addList(L);
for (int j=0;j<10;j++) {
InsertList(L, 1, j);
}
int e = -1;
DeleteList(L, 1, e);
printf("\n 删除元素: %d \n", e);
putList(L);
if (empty(L)) {
printf("\n 是空表 \n");
}else {
printf("\n 非空表 \n");
}
printf(" 表长度:%d ", Length(L));
}