【无标题】单链表相关操作

本文介绍了单链表数据结构,包括节点的定义(包含数据域和指针域)以及三种基本操作:1)在链表头或尾添加元素,时间复杂度为O(1);2)删除指定值的节点,也具备O(1)的时间复杂度;3)根据索引或值查找节点,时间复杂度为O(N)。
摘要由CSDN通过智能技术生成

链表之单链表操作

用逻辑上的“链”将节点串联起来的数据结构。

结点:就是一个结构体对象,节点中含有数据域、指针域。指针域中存放的是节点的地址。
在这里插入图片描述

typedef struct node_s{
	int data;
	struct node_s* next;
}Node;

//
typedef struct {
	Node* head;		//链表头部
	Node* tail;		//链表尾部
	int size;		//链表长度
}List;

单链表

基本操作:

​ 1.添加元素(在某个节点后边) O(1)

void add_before_head(List* list, int val) {
	//创建节点
	Node* new_node = malloc(sizeof(Node));
	if (!new_node) {
		printf("create node failed.\n");
		exit(1);
	}

	//初始化
	new_node->data = val;
	new_node->next = list->head;
	//链接
	if (list->tail == NULL) {
		list->tail = new_node;
	}
	list->head = new_node;
	list->size++;
}
void add_behind_tail(List* list, int val) {
	//创建节点
	Node* new_node = malloc(sizeof(Node));
	if (!new_node) {
		printf("create node failed.\n");
		exit(1);
	}
	//初始化
	new_node->data = val;
	if (list->tail) {
		list->tail->next = new_node;
		list->tail = new_node;
	} else{
		list->head = list->tail = new_node;
	}
	//链接
	list->tail->next = NULL;
	list->size++;

}


void add_node(List* list, int idx, int val) {
	//参数校验
	if (idx < 0 && idx > list->size) {
		printf("insert poistion idx:%d is illegal.\n",idx);
		exit(1);
	}

	if (idx == 0) {
		add_before_head(list,val);
		return;
	}

	if (idx == list->size) {
		add_behind_tail(list,val);
		return;
	}

	//中间插入
	int i = 0;
	Node* tmp = list->head;
	while (i < idx - 1 && tmp) {
		tmp = tmp->next;
		i++;
	}
	Node* new_node = malloc(sizeof(Node));
	if (!new_node) {
		printf("create node failed.\n");
		exit(1);
	}
	new_node->data = val;
	//链接
	new_node->next = tmp->next;
	tmp->next = new_node;
	//更新链表长度
	list->size++;
}

2.删除元素(在某个节点后边)O(1)

void delete_node(List* list, int val) {
	Node* pre = NULL;
	Node* cur = list->head;
	
	while (cur && cur->data != val) {
		pre = cur;
		cur = cur->next;
	}
	if (cur == NULL) {
		printf("not value is %d of node.\n",val);
		return;
	}
	if (cur == list->head) {	//头部删除
		pre = cur;
		cur = cur->next;
		list->head = cur;
		list->size--;
		free(pre);
		return;
	}
	if (cur == list->tail) {
		pre->next = cur->next;
		list->tail = pre;
		free(cur);
		list->size--;
		return;
	}
	pre->next = cur->next;
	list->size--;
	free(cur);
}

​ 3.查找

​ a.根据索引查找节点O(N)

Node* find_by_index(List* list, int idx) {
	if (idx < 0 && idx > list->size - 1) {
		return NULL;
	}
	int i = 0;
	Node* cur = list->head;
	while (i < idx && cur) {
		i++;
		cur = cur->next;
	}
	return cur;
}

​ b.查找链表中与特定值相等的节点O(N)

Node* search_for_value(List* list, int val) {
	Node* cur = list->head;
	while (cur && cur->data != val) {
		cur = cur->next;
	}
	return cur;	//Node* or NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值