链表的使用

链表

c 复制代码
typedef struct {
	int val;
    struct ListNode *next;
}ListNode;

初始化

c 复制代码
ListNode* InitListNode(int val){
    ListNode *a ;
    a = (ListNode *)malloc(sizeof(ListNode));
    a->next = NULL;
    a->val = val;
    return a;
}

插入

c 复制代码
//在a后面插入b
void insert(ListNode *a , ListNode *b)
{
    b->next = a->next;
    a->next = b;
}

删除

c 复制代码
//删除a后面的节点
void del( ListNode * a){
    if(!a->next) return ;
    ListNode * p = a->next;
    ListNode * n = p->next;
    a->next = n;
    free(p);
}

访问节点

c 复制代码
ListNode *access(ListNode *n,int index){
    for (int i=0;i<index;i++){
        if(n->next==NULL) return NULL;
        n=n->next;
    }
    return n;
}

查找

c 复制代码
int find(ListNode * node,int target){
    int index = 0;
    while(node){
        if(node->val == target) return index;
        node = node->next;
        index++;
    }
    reutrn -1;
}

双向链表

c 复制代码
typedef struct DoublyListNode{
   int val;
   struct DoublyListNode *prev;
   struct DoublyListNode *next;
} DoublyListNode;

初始化

c 复制代码
ListNode *newDoublyListNode(int val){
    DoublyListNode *node;
    node = (DoublyListNode *)malloc(sizeof(DoublyListNode));
    node->prev = NULL;
    node->next = NULL;
    node->val = val;
}

析构函数

c 复制代码
void delDoublyListNode(DoublyListNode *node){
    free(node);
}

寻找第i个节点

c 复制代码
DoublyListNode GetElem(DoublyListNode * node, int i){
    for(int j=0;j<i;j++){
        if(node->next == NULL){
            printf("i too large!!\n");
            return NULL;
        }
        node = node->next;
    }
    return node;
}

插入

c 复制代码
//s插入到n的前面
void find(DoublyListNode *n ,DoublyListNode *s){
    s->next = n->next->prev;
    s->prev = n;
    n->next->prev = s;
    n->next = s;
}

删除

c 复制代码
void delete(DoublyListNode *s){
    
    s->prev->next = s->next;
    s->next->prev = s->prev;
    free(s);
}
相关推荐
草莓熊Lotso32 分钟前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
Andrew_Xzw2 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
还有几根头发呀3 小时前
UDP 与 TCP 调用接口的差异:面试高频问题解析与实战总结
网络·网络协议·tcp/ip·面试·udp
超的小宝贝3 小时前
数据结构算法(C语言)
c语言·数据结构·算法
凤年徐5 小时前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
Demisse10 小时前
[华为eNSP] OSPF综合实验
网络·华为
闪电麦坤9510 小时前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
工控小楠10 小时前
DeviceNet转Modbus TCP网关的远程遥控接收端连接研究
网络·网络协议·devicenet·profient
搬码临时工10 小时前
电脑同时连接内网和外网的方法,附外网连接局域网的操作设置
运维·服务器·网络
小熊猫写算法er11 小时前
终极数据结构详解:从理论到实践
数据结构