单链表L是一个递减有序表,试编写一个高效算法,删除表中值大于min且小于max的结点

#include <iostream>
using namespace std;

template<typename T> class Node{
	public:
		T data;
		Node* next;
	public:
		//初始化
		Node(){
			this->next = NULL;
			this->data = 0; 
		}
		//打印
		void print(){
			Node* p = this->next;
			while(p!=NULL){
				cout<<p->data<<" ";
				p = p->next;
			}
			cout<<endl;
		}
		//有序创建链表  递减 
		void creatSort(T ele){
			Node* p = this; //遍历指向当前结点 
			Node* pr = this;	//指向当前结点的前一结点
			while( (p=p->next)!=NULL && p->data>ele ){
				pr = p;
			} 
			Node* cur = new Node;
			cur->data = ele;
			pr->next = cur;
			cur->next = p;
		} 
		//区间删除
		void del(int min, int max){
			Node* p = this->next;
			Node* pr = this;
			while(p!=NULL){
				if(p->data>=min && p->data<=max){
					pr->next = p->next;
					delete p;
					p = pr->next;
				}else{
					p = p->next;
					pr = pr->next;
				}
			}
		} 
}; 

int main(){

	Node<int> node3;
	for(int i=1; i<=10; i++){
		node3.creatSort(i);
	}
	node3.print();
	node3.del(2,5);
	node3.print();
	
	return 0;
}

发布了213 篇原创文章 · 获赞 104 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42363032/article/details/104182581