有序双链表的建立

/*
**把一个值插入到一个有序双链表,first是一个指向根节点的指针,
**newValue是欲插入的新值。
**返回值:如果欲插值原先已存在于链表中,函数返回0;
**如果内存不足导致无法插入,函数返回-1;如果插入成功,函数返回1。
*/
#include <stdio.h>
#include <stdlib.h>

typedef struct NODE{
    struct NODE *left;
    struct NODE *right;
    int value;    
}Node;

int dListInsert(Node **first,int newValue)
{
    Node *current = *first;
    Node *newNode,*pre = NULL;
    
    while(current != NULL && current->value < newValue)
    {
        pre = current;
        current = current->right;
    }
    if(current != NULL && current->value == newValue)
        return 0;
        
    newNode = (Node *)malloc(sizeof(Node));
	newNode->value = newValue;
    if(newNode == NULL)
        return -1;
   
    newNode->right = current;                   //1
    newNode->left = pre;                        //2
    if(current != NULL)                                     //链表非空并且插入位置不在链表尾部
        current->left = newNode;                //3
    
    if(current == *first)                                   //新节点插入位置为链表首部或者链表本身为空
        *first = newNode;    
    else 
        pre->right = newNode;                   //4
        
    return 1;        
}

/*
**测试用,输入无序整数,通过调用dListinsert(),
**建立有序且节点值不重复的双链表,然后打印之。
*/
int main(void)
{
    Node *head = NULL;
    Node *temp;
    int count,value;
    
    count = 8;                             //测试整数的个数
    printf("请输入%d个整数:\n",count);
    while(count--)
    {
        scanf("%d",&value);
		dListInsert(&head,value);
    }
    
    temp = head;
    while(temp)
    {
        printf("%d ",temp->value);
        temp = temp->right;
    }
    printf("\n");    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值