/*************************************************************************
> File Name: src/list.c
> Author: yanqi
> Mail: blyanqi@163.com
> Created Time: Sat Apr 9 07:02:45 2022
************************************************************************/
#include<stdio.h>
#include <malloc.h>
#include "../include/list.h"
/**
* 初始化节点
*/
Node * initNode(int val){
Node * node = (Node *)malloc(sizeof(Node));
node->val = val;
node->next=NULL;
return node;
}
/**
* 初始化链表
*/
List * initList(){
List * list = (List *)malloc(sizeof(List));
// 头指针
list->head=NULL;
// 尾指针
list->tail=NULL;
// 长度
list->len=0;
return list;
}
/**
* 销毁链表
*/
void freeList(List *l){
Node *p = l->head;
while(p){
// 临时节点,在栈区不用释放
Node *tmp = p->next;
// 释放当前节点
free(p);
// 下一个节点给p
p=tmp;
}
free(l);
}
/**
* 头部插入
*/
void insertToHead(List *list,int val){
if(!list) return;
Node * node = initNode(val);
// 如果头指针为空,尾指针指向当前节点
if(!list->head) list->tail=node;
// 当前节点的next指向头指针
node->next = list->head;
// 移动头指针
list->head = node;
list->len++;
}
/**
* 尾部插入
*/
void insertToTail(List *list,int val){
if(!list) return;
Node * node = initNode(val);
// 如果头指针为空,则头指针指向当前节点
if(!list->head) list->head=node;
// 尾指针的 next 指向当前节点
list->tail->next = node;
// 移动尾指针
list->tail = node;
list->len++;
}
/**
* 任意处插入
*/
void insertNode(List *list,int idx,int val){
if(!list) return;
// 判读索引合法
if(idx > list->len||idx < 0) return;
// 初始化一个节点
Node * node = initNode(val);
// 索引为0 直接插入头部
Node * p = list->head;
if(idx==0){
insertToHead(list,val);
return;
}
// 移动指针到索引前一个位置
for(int i=0;i<idx-1;i++){
p = p->next;
}
// 先把后继节点给新节点
node->next = p->next;
// 再把当前节点给前一个节点的next
p->next=node;
// 长度增加
list->len++;
}
/**
* 删除节点
*/
void removeNode(List *list,int idx){
if(!list) return;
if(idx >= list->len||idx < 0) return;
Node *p = list->head;
// 移动到索引的前一个节点
for(int i=0;i< idx-1;i++){
p=p->next;
}
// 前一个节点指向当前的下一个节点
p->next = p->next->next;
// 释放当前节点
free(p->next);
// 减少长度
list->len--;
}
/**
* 遍历
*/
void printList(List *list){
printf("list length : %d \n",list->len);
Node * p = list->head;
while(p){
printf("%d ",p->val);
p=p->next;
}
printf("\n-------------------\n");
}
单链表实现
最新推荐文章于 2025-05-02 19:27:56 发布