带头结点单链表增删查操作

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)); 
} 

 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值