#include using namespace std;

typedef int ElemType; // 数据元素的数据类型 typedef struct LNode { ElemType data; // 数据域 struct LNode *next; // 指针域 } LNode, *LinkList;

int ListLength(LinkList L) { int length = 0; LNode *p = L->next; while (p != NULL) { length++; p = p->next; } return length; }

int LocateElem(LinkList L, ElemType e, bool (*compare)(ElemType, ElemType)) { int index = 0; LNode *p = L->next; while (p != NULL) { index++; if (compare(p->data, e)) { return index; } p = p->next; } return 0; }

bool compare(ElemType a, ElemType b) { return a == b; }

bool compareGreater(ElemType a, ElemType b) { return a > b; }

bool compareLess(ElemType a, ElemType b) { return a < b; }

bool compareEqual(ElemType a, ElemType b) { return a == b; }

bool compareNotEqual(ElemType a, ElemType b) { return a != b; }

bool compareGreaterEqual(ElemType a, ElemType b) { return a >= b; }

bool compareLessEqual(ElemType a, ElemType b) { return a <= b; }

bool compareOdd(ElemType a, ElemType b) { return a % 2 == 1; }

bool compareEven(ElemType a, ElemType b) { return a % 2 == 0; }

bool comparePositive(ElemType a, ElemType b) { return a > 0; }

bool compareNegative(ElemType a, ElemType b) { return a < 0; }

bool comparePrime(ElemType a, ElemType b) { if (a < 2) { return false; } for (int i = 2; i * i <= a; i++) { if (a % i == 0) { return false; } } return true; }

bool compareComposite(ElemType a, ElemType b) { if (a < 2) { return true; } for (int i = 2; i * i <= a; i++) { if (a % i == 0) { return true; } } return false; }

Status ListInsert(LinkList &L, int i, ElemType e) { if (i <= 0 || i > ListLength(L) + 1) { return ERROR; } LNode *p = L; for (int j = 1; j < i; j++) { p = p->next; } LNode *newNode = new LNode; newNode->data = e; newNode->next = p->next; p->next = newNode; return OK; }

int main() { LinkList L = new LNode; L->next = NULL;

ListInsert(L, 1, 1);
ListInsert(L, 2, 2);
ListInsert(L, 3, 3);

cout << "Length of L: " << ListLength(L) << endl;

ElemType e = 2;
int index = LocateElem(L, e, compare);
if (index == 0) {
    cout << "Element '" << e << "\' not found in L." << endl;
} else {
    cout << "Element '" << e << "\' found at position " << index << " in L." << endl;
}

ListInsert(L, 2, 4);

return 0;

}


原文地址: https://www.cveoy.top/t/topic/o7i8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录