为链表的输入排序

// 先声明一个可串行化的链表指针
CObList * plist ;

//删除一个元素
void CTestView::RemoveElemToList(CObList *pList, int num)
{    
    //循环遍历查找
    POSITION pos1, pos2;
    CObject* pa;    
    for (pos1 = pList->GetHeadPosition(); (pos2 = pos1) != NULL;; pList->GetNext(pos1))
    {
        
        if (*(CAge*)pList->GetNext(pos1) == CAge(num))
        {
            pa =  pList->GetAt(pos2); // Save the old pointer for            .
            pList->RemoveAt(pos2);
            delete pa; // Deletion avoids memory leak.
        }
    }

}


//插入一个元素
void CTestView::InsertElemToList(CObList *pList, int num)
{
     //为用户的输入设置限制    

     if(num > 0)
     {    
         
         //以下功能为链表的输入排序
        
         if(pList->IsEmpty())
         {
             pList->AddHead(new CAge(num));
         }
         
         else
             
         {
             POSITION pos1 = pList->GetHeadPosition();
             POSITION pos2 = pList->GetTailPosition();
             
             CAge* aa = (CAge*)pList->GetAt(pos1);
             CAge* bb = (CAge*)pList->GetAt(pos2);
             
             
             if((UINT)num < aa->GetValue())
             {    pList->AddHead(new CAge(num));
                return;
             }
             
             if((UINT)num > bb->GetValue())            
             {    pList->AddTail(new CAge(num));
                return ;
             }

             
             int j = 0;
             for (POSITION  pos3 = pList->GetHeadPosition(); pos3 != NULL;; pList->GetNext(pos3))
             {
                 CAge* cc = (CAge*)pList->GetAt(pos3);
                                  
                 if( (UINT)num == cc->GetValue() ) return;    //如果有相同的元素,直接返回
                 
                 if ( (UINT)num  >cc->GetValue() )    j++;        
                 
             }
             
             POSITION pos4  = pList->FindIndex(j);
             pList->InsertBefore(pos4, new CAge(num));                 
         }     
        
    }

}

//显示链表内的元素
void CTestView::OnDrawList(CObList *pList, CDC *pDC)
{
    CString str ;    
    int i = 0;    
    //循环遍历
    POSITION pos ;    
    for (pos = pList->GetHeadPosition();  pos != NULL; pList->GetNext(pos))
    {        
        CAge* pa = (CAge*) pList->GetAt(pos); // Save the old pointer for        
        str.Format("%d--%d",i , pa->GetValue()) ;
        pDC->TextOut(100, i*20 ,str);
        i++;    
    }    

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值