链表之单链表操作
用逻辑上的“链”将节点串联起来的数据结构。
结点:就是一个结构体对象,节点中含有数据域、指针域。指针域中存放的是节点的地址。
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;
}