有必要从列表的前 n 个元素中删除最大的元素。不知何故,我不知道该怎么做。请告诉我该怎么做。
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
#define List struct list
List
{
int Dn;
List* Nx;
};
class cList
{
protected:
List* p;
public:
cList() : p(NULL) {}
~cList();
int Empty() { return p == NULL; }
void AddHead(int D)
{
List* q = new(List);
q->Dn = D;
q->Nx = p;
p = q;
}
void Display();
void AddEnd(int D);
long Len();
void DelFirst()
{
List* q = p;
p = p->Nx;
delete(q);
}
};
void cList::Display()
{
List* t = p;
if (p)
while (t)
{
cout << t->Dn << " ";
t = t->Nx;
}
else cout << "->|";
cout << endl;
};
void cList::AddEnd(int D)
{
List* q = new List;
q->Dn = D;
q->Nx = NULL;
List* t = p;
if (p)
{
while (t->Nx) t = t->Nx;
t->Nx = q;
}
else p = q;
};
long cList::Len()
{
if (p)
{
List* t = p;
long i = 0;
while (t)
{
t = t->Nx;
i++;
};
return i;
};
return 0;
};
cList::~cList()
{
while (!Empty()) DelFirst();
};
int main()
{
cout << "Demo List" << endl;
int A[12] = {23, 19, 14, 43, 17, 22, -31, 46, -7, 2, 64, 53};
cList L1;
cout << "The list is empty?:" << L1.Empty() << endl;
L1.Display();
cout << endl;
for (int i = 0; i < 12; i++) L1.AddEnd(A[i]);
L1.Display();
cout << endl;
cout << "Count Element = " << L1.Len() << endl;
L1.~cList();
system("pause");
return 0;
}
我们使一个变量指向前一个列表节点。起初它是 nullptr,因为在列表的开头没有前一个节点。我们遍历列表,检查谁在内存中更多。如果我们找到竞争对手,我们将指针更改为 PREVIOUS 节点。通过列表后,PREVIOUS 链接到下一个更改为下一个之后的最大值。删除找到最大元素的列表节点。
把算法翻译成C++,我想你不会被报废的。
此外,您还有语法错误:分号没有放在函数定义之后,因为函数定义既不是声明也不是运算符。我删除了这些错误的前半部分,并故意留下其余部分,以便您注意这一点。
第二:您的选择器不是 const 涂层的,即 那些不改变对象状态的函数(它们通常在类中最后声明为良好风格的标志),例如 void Display() const;明确表达您不改变对象状态的意图。
第三:您不需要显式调用类析构函数,无论如何都会调用它,因此显式调用析构函数意味着调用它两次......