【C】单向链表和双向链表的插入

typedef  struct NODE {
    struct NODE *link;
    int         value;
} Node;

typedef struct DNODE {
    struct DNODE *fwd;
    struct DNODE *bwd;
    int value;
} Dnode;

# s11_node.h ###############

#include <stdio.h>
#include <stdlib.h>
#include "s11_node.h"

#define FALSE 0
#define TRUE 1


int d11_insert(register Dnode *proot,int value){
    register Dnode *this;
    register Dnode *next;
    register Dnode *newnode;
    /**
     * 查查value是否存在链表中,如果是就直接返回
     * 否则为值创建一个新节点(“newnode”将指向它)
     * this指向新节点之前那个节点
     * next指向新节点之后那个节点
     */

    for(this=proot; (next = this->fwd) != NULL; this = next){
        if (next->value == value)
            return FALSE;
        if(next->value > value)
            break;
    }

    newnode = (Dnode *)malloc(sizeof(Dnode));

    if(newnode == NULL)
        return FALSE;
    newnode->value = value;

    /*新节点添加到链表中*/
    newnode->fwd = next;
    this->fwd = newnode;

    if(this != proot)
        newnode->bwd = this;
    else
        newnode->bwd = NULL;
    if(next != NULL)
        next->bwd = newnode;
    else
        proot->bwd = newnode;

    return TRUE;
}
/**
 *  单向链表有序插入
 */

int s11_insert(register Node **plink, int new_value)
{
    register Node *current;
    register Node *new;


    /*寻找正确的插入位置*/
    while((current = *plink) != NULL && current->value < new_value){
        plink = &current->link;
    }

    /*为新节点分配内存*/

    new = (Node *)malloc(sizeof(Node));
    if(new == NULL){
        return FALSE;
    }

    new->value = new_value;

    /*链表中插入新节点*/

    new->link = current;
    *plink = new;
    return TRUE;
}


int main(int argc, char **argv)
{
    Node *p1;
    p1 = NULL;
    int i;
    for(i=0;i<20;i+=2)
        s11_insert(&p1,i);

    s11_insert(&p1, 15);
    while(p1!=NULL){
        printf("%d\n",p1->value);
        p1 = p1->link;
    }
    return EXIT_SUCCESS;

}

# main.c ######
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

深入沟通_it6688668

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值