单链表实现

/*************************************************************************
	> 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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值