#include<iostream>
using namespace std;
struct Node{
int x;
Node *next;
};
typedef struct Node * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
void Print(List L)
{
Position P = L;
while (P != NULL)
{
cout << P->x << " ";
P = P->next;
}
}
List InsertBeg(List L, int x){
Node *tmp = new Node;
tmp->x = x;
if (L == NULL)
{
tmp->next = NULL;
L = tmp;
}
else
{
tmp->next = L;
L = tmp;
}
return L;
}
Position FindLast(List L){
Position P = L;
if (L != NULL)
while (P->next != NULL)
P = P->next;
return P;
}
List deleteFirst(List L) {
Position P = L;
L = L->next;
P->next = NULL;
delete P;
return L;
}
Position FindX(List L, int x){
Position P = L;
while (P != NULL && P->x != x){
P = P->next;
}
return P;
}
Position FindPrevPos(List L, Position P){
Position prev = L;
if (L != NULL)
if (P != NULL && (P != L))
while (prev->next != P)
prev = prev->next;
return prev;
}
List deleteLast(List L) {
Position last = FindLast(L);
Position prev = FindPrevPos(L, last);
prev->next = NULL;
delete last;
return L;
}
List deleteX(List L, int x)
{
Position P = FindX(L, x);
if (P == L)
L = deleteFirst(L);
else if (P->next == NULL)
L = deleteLast(L);
else {
Position prev;
prev = FindPrevPos(L, P);
prev->next = P->next;
P->next = NULL;
delete P;
}
return L;
}
List deleteeven(List L){
Position P = L;
while (P != NULL)
{
if (P->x % 2 == 0)
P = deleteX(L, P->x);
P = P->next;
}
return L;
}
int main()
{
List L = NULL;
L = InsertBeg(L, 4);
L = InsertBeg(L, 8);
L = InsertBeg(L, 1);
L = InsertBeg(L, 21);
Print(L);
L = deleteeven(L);
cout << "After deleting the even numbers";
Print(L);
cin.get();
cin.get();
return 0;
}
我需要删除赔率而不是平均值,我有这个用于平均但我需要修改它并使其删除赔率,我尝试并且我无法修改它以删除赔率!如果你可以修改它并使其删除赔率,我会非常感激。
谢谢!
答案 0 :(得分:1)
使用std :: list是一个很好的解决方案,你可以像这样定义你的数字:
list<int> numbers;
并使用以下代码行删除偶数:
numbers.remove_if([](int value) { return !(value % 2); });
答案 1 :(得分:0)
试试这个。
List RemoveOdd(List L) {
Position* prev = &L;
Position cur = L;
while (cur) {
if (cur->x % 2) {
*prev = cur->next;
delete cur;
cur = *prev;
} else {
prev = &cur->next;
cur = cur->next;
}
}
return L;
}