在有序链表中插入结点

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


struct node {
    int value;
    struct node *next;
};

struct node *inset_into_ordered_list(struct node *list, struct node *new_node);

int main(void)
{
    struct node *p1 = malloc(sizeof(struct node));
    struct node *p2 = malloc(sizeof(struct node));    
    struct node *p3 = malloc(sizeof(struct node));    
    
    struct node *ultimo = malloc(sizeof(struct node));    
    
    p1->value = 10;
    p1->next = p2;
    
    p2->value = 50;
    p2->next = p3;
    
    p3->value = 80;
    p3->next = NULL;

    ultimo->value = 142;
    ultimo->next = NULL;    
    
    p1 = inset_into_ordered_list(p1, ultimo);
    
    return 0;
}

struct node *inset_into_ordered_list(struct node *list, struct node *new_node)
{
    struct node *cur = list, *prev = NULL;
    while (cur->value <= new_node->value) {
        prev = cur;
        if (cur->next == NULL) {                //nel caso nell'ultimo poszione della lista
            new_node = cur->next;
            return list;
        }
        else    
        cur = cur->next;
    }
    if (prev == NULL) {                            // nel caso nel primo poszione della lista
        new_node->next = cur;    
        return new_node;
    }
    
        
    prev->next = new_node;
    new_node->next = cur;
                        
    
    return list;
}                                                                                      
    
   

必需注意,当要插入的结点在链表的第一位,和最后一位的特殊情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值