zoukankan      html  css  js  c++  java
  • 保证值有序的链表插入算法

    在做链表插入时,保证链表中的值是有序的,比如从小到大,依次递增。

    以下是今天写的一段代码的修改版。

    typedef struct Node{
        int value;
        Node *next;
    } Node;
    
    typedef struct NodeHead{
         int counter;
         Node *p;
    } NodeHead;
    
    //该算法实现对链表进行插入时,保证值是从小到大进行变化的。
    void insert(Node *&nd, NodeHead *&hd) { if(null==hd)//hd 还没有被建立 { hd = (NodeHead*)malloc(sizeof(NodeHead)); hd->counter=0; hd->p = null; } Node *pre=hd->p; Node *last=hd->p; if(pre->next == null && last->next == null)//若果链表中还没有值,此时应插入到第一个节点, 此处也可以用if(0==hd->counter)代替 { hd->p = nd; nd->next = null; hd->counter++; } else { while(last!=null) { if(nd->value < last->value) { if(pre== hd->p && pre ==last)//如果是应该插在最前面 { hd->p = nd; } else { pre->next=nd; } hd->counter++; break; } else if (nd->value == last->value) { cout<<"the value has exist"<<endl; break; } else { pre = last; last = last->next; } } if(null == last)//如果值应该插在最后面 { pre->next = nd; nd->next=null; hd->counter++; } } }
  • 相关阅读:
    代理模式
    适配器模式
    策略模式
    原型模式
    内存溢出
    jvm常用参数
    单例模式
    抽象工厂
    工厂方法模式
    选择器代码
  • 原文地址:https://www.cnblogs.com/jiayouwyhit/p/3684096.html
Copyright © 2011-2022 走看看