#include<iostream>
#include<cstdio>
#define ERROR 0
#define OK 1
using std::cin;
using std::cout;
typedef int Status;
typedef size_t Posit_t;
typedef size_t Size_t;
template<class Elem_t>
struct Node {
struct Node *next;
Elem_t data;
};
template<class Elem_t>
class LNode {
public:
LNode() = default;
//O(1)
struct Node* initNode(Elem_t e) {
struct Node* newNode;
newNode->data = e;
newNode->next = NULL;
return newNode;
}
//O(1)
Status isEmpty (const struct Node* node)const {
return node == NULL;
}
//O(N)
Posit_t findVal(struct Node* node,Elem_t e) {
int cnt = 1;
while (node != NULL) {
if(node->data == e)
{
return cnt;
}
else{
node = node->next;
cnt ++;
}
}
return ERROR;
}
//O(N)
Size_t getLen(struct Node* node)const{
Size_t len = 1;
for(auto it=node;it != NULL;it = it->next){
len ++;
}
return len;
}
//O(N)
Status eraseNode(Posit_t p, struct Node* node) {
if(isEmpty(node) || p<0 || node == NULL) return ERROR;
else{
int cnt = 1;
while(p-1 != cnt){
cnt ++;
node = node->next;
}
node->next = node->next->next;
return OK;
}
}
//O(N)
Status insertNode(Posit_t p, struct Node* node,Elem_t e){
int cnt = 1;
if(p<0 || node == NULL) return ERROR;
while(p-1 != cnt){
cnt ++;
node = node->next;
}
struct Node* t;
t->data = e;
t->next = node->next;
node->next = t;
return OK;
}
Elem_t findMax(struct Node* node){
try(
Elem_t maxVal = node->data;
for(auto it=node;it != NULL;it = it->next){
if(maxVal < node->data)
maxVal = node->data;
}
return maxVal;
)catch(node == NULL){
throw ERROR;
}
}
Elem_t findMin(struct Node* node){
try(
Elem_t minVal = node->data;
for(auto it=node;it != NULL;it = it->next){
if(minVal > node->data)
minVal = node->data;
}
return minVal;
)catch(node == NULL){
throw ERROR;
}
}
//O(N)
void showNode(struct Node* node){
for(auto it=node;it != NULL;it = it->next){
cout << "[" << node->data << "]->";
}
}
~LNode();
};
C++ 单链表
最新推荐文章于 2024-05-16 21:12:43 发布