自学内容网 自学内容网

链表的使用

链表

typedef struct {
int val;
    struct ListNode *next;
}ListNode;

初始化

ListNode* InitListNode(int val){
    ListNode *a ;
    a = (ListNode *)malloc(sizeof(ListNode));
    a->next = NULL;
    a->val = val;
    return a;
}

插入

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

删除

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

访问节点

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

查找

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

双向链表

typedef struct DoublyListNode{
   int val;
   struct DoublyListNode *prev;
   struct DoublyListNode *next;
} DoublyListNode;

初始化

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

析构函数

void delDoublyListNode(DoublyListNode *node){
    free(node);
}

寻找第i个节点

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;
}

插入

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

删除

void delete(DoublyListNode *s){
    
    s->prev->next = s->next;
    s->next->prev = s->prev;
    free(s);
}

原文地址:https://blog.csdn.net/2301_80360664/article/details/143657247

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!