// 先声明一个可串行化的链表指针
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++;
}
}