栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

单链表实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单链表实现


#include
#include 
#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;inext;
    }
    // 先把后继节点给新节点
    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");
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879632.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号