C++ 单链表

#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();
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值